Python pytz Converting a timestamp (string format) from one timezone to another

Angela picture Angela · Sep 7, 2011 · Viewed 14.5k times · Source

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

Answer

six8 picture six8 · Sep 7, 2011

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))