Python pytz Convert timestamp (string format) from one time zone to another

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

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

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

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

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

UPDATE

Thanks, Cixate. I just found a solution that is very similar to yours. Found useful links - LINK1 and LINK2

Posting a solution for all the benefits

 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 
+8
python timezone timestamp pytz
source share
1 answer

datetime.astimezone will do the basic conversion if you have a datetime object. If you are trying to get a datetime object from a string, pip install python-dateutil and it is 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)) 
+9
source share

All Articles