如何获取当前时间?


当前回答

从中尝试箭头模块http://crsmithdev.com/arrow/:

import arrow
arrow.now()

或UTC版本:

arrow.utcnow()

要更改其输出,请添加.format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

对于特定时区:

arrow.now('US/Pacific')

一小时前:

arrow.utcnow().replace(hours=-1)

或者如果你想要要点。

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

其他回答

这应该行得通

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'
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

示例输出:“2013-09-18 11:16:32”

请参阅strftime指令列表。

获取当前时间并将其转换为字符串:

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

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

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

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