0

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.

3
  • What have you tried yourself?
    – DeepSpace
    Commented Sep 23, 2018 at 13:59
  • 2
    This is not a tutorial site. DO your research and make an attempt. Then ask here if something is confusing or giving you issues, and provide sample code. You must help yourself first, then come here for more clarification. Commented Sep 23, 2018 at 14:01
  • 1
    Yes, i tried. Thanks for enlightening me about format of stackoverflow. Will take care in future. Your answer really helped me a lot. Commented Sep 23, 2018 at 15:09

2 Answers 2

2

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)
1
  • 1
    Don't know why it was voted down, seems like a perfectly resonable answer....
    – ckm
    Commented Nov 16, 2020 at 2:45
-2

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.