【问题标题】:Getting Python to Print the Hour of Day让 Python 打印一天中的时间
【发布时间】:2014-03-28 02:25:38
【问题描述】:

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

import time

time = time.asctime()

print(time)

我最终得到以下结果:

'Tue Feb 25 12:09:09 2014'

如何让 Python 只打印小时?

【问题讨论】:

  • 您可以查看文档:docs.python.org/2/library/time.html。我同意“时间”是一个相当老式的库,它不是面向对象的
  • 你不应该使用 'time' 作为变量名:这样你就用你的变量 'time' 替换了库 'time'

标签: python python-3.x time


【解决方案1】:

你可以使用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() 都使用您计算机的本地时区概念(即,“天真”日期时间对象)。

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

【讨论】:

  • 传递最佳答案,因为它避免了使用不起眼的 time 模块。
【解决方案2】:
import time
print (time.strftime("%H"))

【讨论】:

    【解决方案3】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2011-08-10
      • 2018-02-24
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多