16

I have a timestamp with timezone information in string format and I would like to convert this to display the correct date/time using my local timezone. So for eg... I have

timestamp1 = 2011-08-24 13:39:00 +0800

and I would like to convert this to say timezone offset +1000 to dsiplay

timestamp2 = 2011-08-24 15:39:00 +1000

I have tried using pytz but couldnt find many examples showing how to use the offset information. One other link that I found on stackoverflow which depicts this exact problem is here. I was hoping there was some better way I could handle this using pytz. Thanks for all suggestions in advance :).

UPDATE

Thanks Cixate. I just found the solution which is very similar to yours. Found these links helpful - LINK1 and LINK2

Posting the solution for everyones benefit

from datetime import datetime
import sys, os
import pytz
from dateutil.parser import parse

datestr = "2011-09-09 13:20:00 +0800"
dt = parse(datestr)
print dt
localtime = dt.astimezone (pytz.timezone('Australia/Melbourne'))
print localtime.strftime ("%Y-%m-%d %H:%M:%S")
2011-09-09 15:20:00
1
  • Consider marking Cixate's answer as correct by clicking its checkbox, since your final solution is close to Cixate's suggestion. Commented Sep 7, 2011 at 18:01

1 Answer 1

14

datetime.astimezone will do your basic conversion once you have a datetime object. If you're trying to get a datetime object from a string, pip install python-dateutil and it's as simple as:

>>> from dateutil.parser import parse
>>> from dateutil.tz import tzoffset
>>> dt = parse('2011-08-24 13:39:00 +0800')
datetime.datetime(2011, 8, 24, 13, 39, tzinfo=tzoffset(None, 28800))
>>> dt.astimezone(tzoffset(None, 3600))
datetime.datetime(2011, 8, 24, 6, 39, tzinfo=tzoffset(None, 3600))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Cixate..I just got the solution using dateutil.parser and datetime.astimezone. My solution is a bit different to yours. Forgive my ignorance, but could you please elaborate on how you retrieve the timezone information using "tzoffset(None, 3600)"
In your example you wanted to translate to an offset of "+1000", unfortunately I read that as "+0100" but the principal is the same. The first parameter of tzoffset() is a name, which can be None if you don't care to know it. The second is the offset from UTC in seconds. So 3600 for 1 hour or 36000 for 10 hours.
Thanks Cixate for the explanation.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.