Daniela
Daniela

Reputation: 911

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'

Upvotes: 5

Views: 28218

Answers (1)

Rakesh
Rakesh

Reputation: 82765

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

Upvotes: 10

Related Questions