如何在python中将小时数添加到当前时间
- 2025-04-15 09:20:00
- admin 原创
- 36
问题描述:
我可以获取如下当前时间:
from datetime import datetime
str(datetime.now())[11:19]
结果
'19:43:20'
现在,我尝试添加9 hours
上述时间,如何在 Python 中将小时数添加到当前时间?
解决方案 1:
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:
导入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如何处理日期和时间字段
解决方案 3:
这是一个对于当今(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())
日期时间
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
解决方案 4:
这对我来说不仅适用于小时工作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))
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD