简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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