简体   繁体   中英

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM