5

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'
1
  • 1
    Your import is wrong. Since you're importing Timedelta directly using "from ... import ..." You don't need to write datetime.timedelta but instead just timedelta Commented Feb 8, 2019 at 12:06

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.