python - Localize datetime (timezone aware) from timezone offset -


i have utc timestamp , timezone offset timestamp (both in milliseconds):

utc_time = 1394452800000 timezoneoffset = -14400000 

if wanted datetime :

print datetime.utcfromtimestamp(utc_time/1000) >>>2014-03-10 12:00:00 

how can localize datetime final object timezone aware?

if divide timezoneoffset, -14400000/(3600*1000) = -4 (hours). final output should be:

>>>2014-03-10 08:00:00-04:00 

my try:

from pytz import timezone dateutil.tz import tzoffset  utc_time = 1394452800000 timezoneoffset = -14400000  tzinfooff = tzoffset(none, timezoneoffset/1000)  print timezone(tzinfooff).localize( datetime.utcfromtimestamp(utc_time/1000) )  >>>traceback (most recent call last):   file "/users/dionysis_lorentzos/desktop/cmdline copy.py", line 25, in <module>     print timezone(tzinfo2).localize( datetime.utcfromtimestamp(time/1000) ).isoformat()   file "/usr/local/lib/python2.7/site-packages/pytz/__init__.py", line 162, in timezone     if zone.upper() == 'utc': attributeerror: 'tzoffset' object has no attribute 'upper' 

you need use just dateutil.tz.tzoffset() type; pytz.timezone takes names, not dateutil.tz objects.

the .localize() method needed pytz-supplied timezones contain historic offsets well, , need applied datetime object using little more care .replace() can do.

if timestamp unix epoch value in utc, use fromtimestap timezone second argument:

>>> print datetime.fromtimestamp(utc_time/1000, tzinfooff) 2014-03-10 08:00:00-04:00 

or translate utc, using datetime.astimezone():

>>> dateutil.tz impor tzutc >>> dt_utc = datetime.utcfromtimestamp(utc_time/1000).replace(tzinfo=tzutc()) >>> print dt_utc.astimezone(tzinfooff) 2014-03-10 08:00:00-04:00 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -