让Python打印出当前小时数

18

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

import time

time = time.asctime()

print(time)

我最终得到了以下结果:

'Tue Feb 25 12:09:09 2014'

如何让Python仅打印小时?


你可以查看文档:http://docs.python.org/2/library/time.html。我同意“time”是一个相当老式的库,不太面向对象化。 - Don
3
不应该将“time”用作变量名:这样你会用你的变量“time”替换掉库中的“time”。 - Don
3个回答

42
你可以使用 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()这两个函数都使用计算机的本地时区(即“naive” datetime对象)。
如果您想使用时区信息,则不那么容易。您可以使用Python 3.2+中的datetime.timezone或使用第三方库pytz。我假设您的计算机时区设置正确,并且使用一个纯日期时间对象相对容易。

毫无疑问,这是最好的答案,因为它避免了使用令人失望的“time”模块。 - Adam Smith

11
import time
print (time.strftime("%H"))

7

time.asctime()会创建一个字符串,因此提取小时部分很困难。相反,获取合适的time.struct_time对象,该对象直接公开组件:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接