如何获取当前时间?


当前回答

对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)

其他回答

下面是根据您的问题只显示时间的代码:

 from datetime import datetime
 time= datetime.now()
 b = time.strftime("%H:%M:%S")
 print(b)

使用datetime.now()获取当前日期和时间。然后使用.strftime获取所需值,即仅时间。

strftime用于检索所需的输出或根据需要更改默认格式。

如果您只希望当前时间戳以毫秒为单位(例如,测量执行时间),也可以使用“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))

这应该行得通

import time

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("The current time is", current_time)

与Harley的答案类似,但使用str()函数实现一种更快速、更易于阅读的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

Do

from time import time

t = time()

t-浮点数,适用于时间间隔测量。

Unix和Windows平台有一些不同。