Search code examples
pythontimezonepymongopytz

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?


Solution

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