简体   繁体   中英

Convert UTC native datetime to Eastern tine native datetime for pymongo

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?

After a bit more goggling, I found this question , which led me to the answer.

  1. Set the UTC timezone to the native UTC datetime
  2. Convert that to eastern time
  3. Get the UTC offset of that as a timedelta
  4. 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 

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).

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.

Also note that if Mongo connection is not opened as timezone aware you just get naive datetime out of the database.

from pymongo import Connection
# Create a timezone aware connection
connection = Connection('localhost', 27017, tz_aware=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM