Search code examples
pythondatetimetimedelta

Python - Adding offset to time


I have a time string, say

str = "2018-09-23 14:46:55"

and an offset

offset = "0530"

I want to get str2 with offset added, ie

str2 = "2018-09-23 20:16:55"

Please guide.


Solution

  • You can use the datetime module:

    from datetime import datetime, timedelta
    
    x = "2018-09-23 14:46:55"
    offset = "0530"
    
    res = datetime.strptime(x, '%Y-%m-%d %H:%M:%S') + \
          timedelta(hours=int(offset[:2]), minutes=int(offset[2:]))
    
    print(res)
    
    datetime.datetime(2018, 9, 23, 20, 16, 55)