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
Get the current time using the datetime. now() function and pass the above second−time zone i.e 'US/Eastern' time zone as an argument to it(Here it converts the current date and time to the 'US/Eastern' timezone). Use the strftime() function to format the above datetime object and print it.
To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz. utc)'.
It returns the list and set of commonly used timezones with pytz.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With