我可以得到当前时间如下:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
现在,我试图将9 hours
添加到上述时间,如何在 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

>>> 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
and strftime
behavior以更好地了解 python 如何处理日期和时间字段
这适用于我使用seconds
不是小时,也使用一个函数转换回 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 从 timestring 创建一个 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..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())
日期时间
https://docs.python.org/3/library/datetime.htmlstrftime-and-strptime-format-code
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codestimedelta
https://docs.python.org/3/library/datetime.html#datetime.timedeltazoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(45条)