简体   繁体   English

在 Python 中为日期添加时间

[英]Adding time to a date in Python

I would like to add time to a date.我想为日期添加时间。 Date and time are strings日期和时间是字符串

12/28/2018 23:30:00

now in this i would like to add Time现在在这里我想添加时间

02:30:00

in output:在输出中:

12/29/2018 02:30

I've tried the following:我尝试了以下方法:

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)

I get the following error:我收到以下错误:

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

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

Ex: 例如:

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)

Note: You have already imported timedelta 注意:您已经导入了timedelta

You can find any help by reading the answers to this question . 您可以通过阅读此问题的答案找到任何帮助。 I think the problem you have is the same as the one shown there. 我认为您遇到的问题与此处显示的问题相同。 I hope you find it useful. 希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM