4

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'
Daniela
  • 861
  • 5
  • 11
  • 28
  • 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` – Ian Rehwinkel Feb 08 '19 at 12:06

1 Answers1

9

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

Rakesh
  • 81,458
  • 17
  • 76
  • 113