如何获取当前时间?


当前回答

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

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

其他回答

这里有很多复杂的解决方案,初学者可能会感到困惑。我发现这是这个问题最简单的解决方案,因为它只返回所问的当前时间(没有虚饰):

import datetime

time = datetime.datetime.now()

display_time = time.strftime("%H:%M")
print(display_time)

如果您希望返回比当前时间更详细的信息,可以按照其他人的建议进行操作:

import datetime

time = datetime.datetime.now()
print(time)

虽然这种方法写起来更短,但它也会返回当前日期和毫秒,这在简单地返回当前时间时可能不需要。

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

.iformat()在文档中,但这里还没有(这与@Ray Vega的回答非常相似):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

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

Do

from time import time

t = time()

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

Unix和Windows平台有一些不同。