gpt4 book ai didi

python - 在 Python 中为日期添加时间

转载 作者:行者123 更新时间:2023-12-04 16:43:19 25 4
gpt4 key购买 nike

我想为日期添加时间。日期和时间是字符串

12/28/2018 23:30:00

现在我想添加时间

02:30:00

在输出中:

12/29/2018 02:30

我尝试了以下方法:

import datetime
from datetime import datetime, timedelta

departure_time = "15:30"
duration = "00:00:50"

#I convert the strings to datetime obj
departure_time_obj = datetime.strptime(departure_time_obj, '%H:%M')
duration_obj = datetime.strptime(duration_obj, '%H:%M:%S')

arrival_time = dtt + datetime.timedelta(duration_obj)
print(arrival_time)

我收到以下错误:

AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

最佳答案

使用 timedelta(hours=duration_obj.hour, minutes=duration_obj.minute, seconds=duration_obj.second)

例如:

from datetime import datetime, timedelta

departure_time = "15:30"
duration = "00:00:50"

#I convert the strings to datetime obj
departure_time_obj = datetime.strptime(departure_time, '%H:%M')
duration_obj = datetime.strptime(duration, '%H:%M:%S')

arrival_time = departure_time_obj + timedelta(hours=duration_obj.hour, minutes=duration_obj.minute, seconds=duration_obj.second)
print(arrival_time)

注意:你已经导入了timedelta

关于python - 在 Python 中为日期添加时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com