如何获取当前时间?


当前回答

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

其他回答

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

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

最快的方法是:

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

为什么不问问美国海军的官方计时员美国海军天文台?

import requests
from lxml import html

page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

如果你住在华盛顿地区(像我一样),延迟可能不会太差。。。

从中尝试箭头模块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 datetime

time = datetime.datetime.now()

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

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

import datetime

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

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