I need to query a mongodb that saves it's dates in the local timezone (Eastern), but I'm working in UTC. How can I convert a UTC native datetime to Eastern tine native datetime for pymongo, accounting for daylight savings?
4 Answers
1
votes
To convert a naive datetime object that represents time in UTC to different timezone:
from datetime import datetime
import pytz
tz = pytz.timezone('US/Eastern') #NOTE: deprecated timezone name
naive_utc_dt = datetime.utcnow() # naive datetime object
utc_dt = naive_utc_dt.replace(tzinfo=pytz.utc) # aware datetime object
east_dt = utc_dt.astimezone(tz) # convert to Eastern timezone
naive_east_dt = east_dt.replace(tzinfo=None) #XXX use it only if you have to
Note: if the source timezone is not UTC then .localize(), .normalize() method should be used.
pytz allows you to handle utc offset changes (not only due to DST) for a given region: today, in the past (many libraries fail here).
1
votes
After a bit more goggling, I found this question, which led me to the answer.
- Set the UTC timezone to the native UTC datetime
- Convert that to eastern time
- Get the UTC offset of that as a timedelta
- Add that to the original datetime
ET = pytz.timezone("America/New_York") def utc_to_et(utcdt): utc_with_tz = utcdt.replace(tzinfo=pytz.UTC) offset = utc_with_tz.astimezone(ET).utcoffset() return utcdt + offset
0
votes
I'm not sure if this is what you mean:
http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone
It allow you to change datetime from one timezone to another.