如何获取当前时间?


当前回答

可以使用ctime()执行此操作:

from time import time, ctime
t = time()
ctime(t)

输出:

2019年9月14日星期六21:27:08

这些输出不同,因为ctime()返回的时间戳取决于您的地理位置。

其他回答

now()的属性可用于获取python中的当前时间:

# importing datetime module for now()
import datetime
    
# using now() to get current time
current_time = datetime.datetime.now()
    
# Printing attributes of now().
print ("The attributes of now() are : ")
    
print ("Year : ", end = "")
print (current_time.year)
    
print ("Month : ", end = "")
print (current_time.month)
    
print ("Day : ", end = "")
print (current_time.day)
    
print ("Hour : ", end = "")
print (current_time.hour)
    
print ("Minute : ", end = "")
print (current_time.minute)
    
print ("Second : ", end = "")
print (current_time.second)
    
print ("Microsecond : ", end = "")
print (current_time.microsecond)

以下是我用来获取时间而不必格式化的内容。有些人不喜欢拆分方法,但它在这里很有用:

from time import ctime
print ctime().split()[3]

它将以HH:MM:SS格式打印。

如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“timeit”模块:

import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))

在Python 3.9中,zoneinfo模块可以用于获取时区,而不是使用第三方库。

要获取特定时区中的当前时间,请执行以下操作:

from datetime import datetime
from zoneinfo import ZoneInfo

datetime.now(tz=ZoneInfo("Europe/Amsterdam"))

对UTC日期时间、本地日期时间使用此方法,并转换上午和下午

import pytz
from datetime import datetime

#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)

#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)