Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an un-aware timestamp into an aware timestamp for UTC conversion

I created a datetime that is unaware using the code below and I need to have it in UTC since the time is in "US/Eastern". I would like to make the datetime aware of EST first then convert to UTC.

import datetime
import pytz
from pytz import timezone
dt = "8/8/2013 4:05:03 PM"
dt = datetime.datetime.strptime(dt,"%m/%d/%Y %I:%M:%S %p")
unaware_est = dt.strftime("%Y-%m-%dT%H:%M:%S")
localtz = timezone('US/Eastern')
utc = localtz.localize(unaware_est)

Error Message:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/druidry-codebase/services/xignite/test.py", line 120, in <module>
    quote_time = localtz.localize(quote_time)
  File "/usr/local/lib/python2.7/dist-packages/pytz-2013b-py2.7.egg/pytz/tzinfo.py", line 303, in localize
    if dt.tzinfo is not None:
AttributeError: 'str' object has no attribute 'tzinfo'
like image 709
Tampa Avatar asked Aug 11 '13 20:08

Tampa


2 Answers

The localize method takes a datetime, not a string. So the call to strftime should be removed.

import datetime
import pytz
from pytz import timezone
dt = "8/8/2013 4:05:03 PM"
unaware_est = datetime.datetime.strptime(dt,"%m/%d/%Y %I:%M:%S %p")
localtz = timezone('US/Eastern')
aware_est = localtz.localize(unaware_est)

This still doesn't give you UTC. If you want that, you need to follow it up with:

utc = aware_est.astimezone(pytz.utc)
like image 196
Matt Johnson-Pint Avatar answered Sep 30 '22 10:09

Matt Johnson-Pint


A Python string and datetime object are not interchangable. You need to convert them explicitly:

from datetime import datetime
import pytz # $ pip install pytz

# convert the time string to a datetime object
dt_str = "8/8/2013 4:05:03 PM"
unaware_est = datetime.strptime(dt_str,"%m/%d/%Y %I:%M:%S %p")

# make it a timezone-aware datetime object 
aware_est = pytz.timezone('US/Eastern').localize(unaware_est, is_dst=None)

# convert it to utc timezone
utc_dt = aware_est.astimezone(pytz.utc) # `.normalize()` is not necessary for UTC

# convert it to a string
print(utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")) # -> 2013-08-08T20:05:03Z

Note: is_dst=None asserts that the input local time exists and it is unambigous. See problems with local time.

like image 24
jfs Avatar answered Sep 30 '22 10:09

jfs