Skip to content
Advertisement

How to add current date with string like ‘1 hour and 5 second ‘ in python

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)

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement