让Python打印一天中的一小时

2024-05-17 10:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码获取时间:

import time

time = time.asctime()

print(time)

我得到了以下结果:

'Tue Feb 25 12:09:09 2014'

我怎样才能让Python只打印一个小时?


Tags: 代码importtime时间febprint小时asctime
3条回答
import time
print (time.strftime("%H"))

您可以使用datetime

>>> import datetime as dt
>>> dt.datetime.now().hour
9

或者,您可以使用today()而不是now():

>>> dt.datetime.today().hour
9

然后插入所需的任何字符串:

>>> print('The hour is {} o\'clock'.format(dt.datetime.today().hour))
The hour is 9 o'clock

请注意,datetime.today()datetime.now()都在使用计算机的本地时区概念(即“天真的”datetime对象)。

如果你想使用时区信息,它不是那么简单。您可以在Python 3.2+上使用datetime.timezone,也可以使用第三方pytz。我假设您的计算机的时区是好的,并且一个简单的(非时区日期时间对象)相当容易使用。

^{}将创建一个字符串,因此很难提取hours部分。相反,获得一个正确的^{}对象,它直接公开组件:

t = time.localtime() # gives you an actual struct_time object
h = t.tm_hour # gives you the hour part as an integer
print(h)

如果你只需要一个小时,你可以一步完成:

print(time.localtime().tm_hour)

相关问题 更多 >