如何在Python中将小时添加到当前时间

249

我可以像下面这样获取当前时间:

from datetime import datetime
str(datetime.now())[11:19]

结果

'19:43:20'

现在,我正在尝试将9小时添加到上面的时间中,在Python中如何添加小时到当前时间?


18
要按照指定格式获取当前时间,请查看 datetime.now().strftime('%H:%M:%S') - eumiro
4个回答

523
from datetime import datetime, timedelta

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

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

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

如果您只需要格式化日期和时间,那么可以使用以下方法:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

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


2
为什么这不是最佳答案?有任何副作用吗?未报告的错误? - Braza
8
@Braza,原帖作者只是没有选择接受它。没有副作用或bug。 - Jon Clements
@JonClements 谢谢您的回复:)。我测试了一下,确认无误。 - Braza
3
这不支持夏令时安全。 - Antti Haapala -- Слава Україні
1
问题要求如何添加小时,但是可以通过两种方式来减去小时:1)使用减法运算符(-)而不是加法运算符(+);根据文档“timedelta对象支持与日期和datetime对象的某些加减运算” 2)向任何timedelta参数传递负值;根据文档,“参数可以是int、long或float,可以是正数或负数”。 - Nate Anderson
1
它在Python2.7上无法工作。有什么解决方案? - shiva

47

导入datetimetimedelta:

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

但更好的方法是:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
你可以参考strptimestrftime的行为,更好地理解Python处理日期和时间字段的方式。

Python文档中的链接提供了有关解析和格式化日期/时间的见解。 - hc_dev

4

这是一个现今(Python 3.9或更高版本)非常重要的答案。

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

    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)

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

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

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

time_modification = datetime.fromtimestamp(timestring.timestamp())

datetime

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

strftime-and-strptime-format-codes

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

timedelta

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

zoneinfo

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


2

我使用这种方法处理 而不是小时,并使用函数将其转换回UTC时间。

from datetime import timezone, datetime, timedelta 
import datetime


def utc_converter(dt):
    dt = datetime.datetime.now(timezone.utc)
    utc_time = dt.replace(tzinfo=timezone.utc)
    utc_timestamp = utc_time.timestamp()
    return utc_timestamp



# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))

utc_time = dt.replace(tzinfo=timezone.utc) 是不必要的 - dttzinfo 已经正确设置为 timezone.utc。此外,您应该只导入模块或其中的特定类,而不是两者都导入。 - FObersteiner
你能否通过发布一个带有对我的回答的参考的答案来给我一些提示?我需要这个,非常感谢您的帮助,我在这方面缺乏经验。 - bbartling
你的意思是导入(import)或者tzinfo吗?关于导入,你在代码片段的第一行中从模块中导入特定的类,在第二行,你导入整个模块(当然包括这些类)。两种方法都可以,只需使用其中一种即可提高可读性;-) - FObersteiner

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