我可以得到现在的时间如下:

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

结果

'19:43:20'

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


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


导入datetime和timedelta:

>>> 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'

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


这适用于我使用秒而不是小时,并使用一个函数转换回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))

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

使用strptime从时间字符串创建一个datetime对象。将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)

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

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