1

I have to add datetime lik '2019-10-18 11:46:08 '+ '5 hour 5 second', 5 hour 5 second is coming from the database and this is not fixed what will be it ie time will be like (15 min, 1 hour 15 min etc) i have tried many thing but getting error how to solve this

import datetime
date_time_str = '2019-10-18 11:46:08 '+ '5 hour 5 second'
date_time_obj = datetime.datetime.strptime(date_time_str, '%b %d %Y %I:%M%p')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Possible duplicate of [What is the standard way to add N seconds to datetime.time in Python?](https://stackoverflow.com/questions/100210/what-is-the-standard-way-to-add-n-seconds-to-datetime-time-in-python) – Attersson Oct 18 '19 at 07:55

1 Answers1

1

Firstly store separately the datetime string and the offset you want to add to the datetime:

date_time_str = '2019-10-18 11:46:08 '
offset = '5 hour 5 second'

Parse the datetime and offset strings:

dt = datetime.datetime.strptime(date_time_str ,'%Y-%m-%d %H:%M:%S ')
offset = datetime.datetime.strptime(offset, '%H hour %S second')

Add the offset to the datetime as a timedelta:

dt + datetime.timedelta(hours=offset.hour, seconds=offset.second)
# datetime.datetime(2019, 10, 18, 16, 46, 13)
yatu
  • 86,083
  • 12
  • 84
  • 139