Saurabh Shrivastava
Saurabh Shrivastava

Reputation: 1484

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.

Upvotes: 0

Views: 3865

Answers (2)

ePandit
ePandit

Reputation: 3243

Use timedelta to add offset to a datetime object.

from datetime import datetime, timedelta

str = "2018-09-23 14:46:55"
str = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
str2 = str + timedelta(hours=5, minutes=30)

print(str2)

Upvotes: -2

jpp
jpp

Reputation: 164623

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)

Upvotes: 2

Related Questions