如何在python中添加当前时间的小时数

Shi*_*dla 133 python time add

我能够得到如下的当前时间:

from datetime import datetime
str(datetime.now())[11:19]
Run Code Online (Sandbox Code Playgroud)

结果

'19:43:20'
Run Code Online (Sandbox Code Playgroud)

现在,我试图添加9 hours到上面的时间,如何在Python中添加当前时间的小时数?

Jon*_*nts 322

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
Run Code Online (Sandbox Code Playgroud)

然后使用字符串格式来获取相关的部分:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
Run Code Online (Sandbox Code Playgroud)

如果您只是格式化日期时间,那么您可以使用:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Run Code Online (Sandbox Code Playgroud)

或者,正如@eumiro在评论中指出的那样 - strftime

  • @Braza OP只是没有选择接受它.没有副作用或错误. (6认同)
  • 但这不是DST安全的. (3认同)
  • 为什么这不是最佳答案?有副作用吗?未报告的错误? (2认同)

mu *_*u 無 34

导入datetimetimedelta

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
Run Code Online (Sandbox Code Playgroud)

但更好的方法是:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
Run Code Online (Sandbox Code Playgroud)

您可以参考strptimestrftime行为以更好地了解python如何处理日期和时间字段


Con*_*nor 5

这是一个对于当今(python 3.9 或更高版本)来说很重要的答案。

使用 strptime 从时间字符串创建日期时间对象。添加 9 小时和 timedelta,并将时间格式与您拥有的时间字符串相匹配。

    from datetime import datetime, timedelta
    from zoneinfo import ZoneInfo

    time_format = "%H:%M:%S"

    timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)

    #You can then apply custom time formatting as well as a timezone.

    TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

    custom_time_format = "%H:%M"

    time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)

Run Code Online (Sandbox Code Playgroud)

虽然我认为应用时区更有意义,但您不一定需要这样做,因此您也可以简单地这样做:

time_format = "%H:%M:%S"

timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)

time_modification = datetime.fromtimestamp(timestring.timestamp())
Run Code Online (Sandbox Code Playgroud)

约会时间

https://docs.python.org/3/library/datetime.html

strftime 和 strptime 格式代码

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

时间增量

https://docs.python.org/3/library/datetime.html#datetime.timedelta

区域信息

https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo