如何获取当前时间?


当前回答

时间模块可以导入各种时间信息,包括睡眠和其他类型的信息,包括当前时间类型

import time
time.strftime("%T", time.localtime())

输出应如下所示

05:46:33
11:22:56
13:44:55
22:33:44
00:00:00

其他回答

如果需要当前时间作为时间对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

这应该行得通

import time

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("The current time is", current_time)
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'

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

前面的答案都是很好的建议,但我发现使用ctime()最简单:

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

这提供了当前本地时间的格式良好的字符串表示。