pythondatetimetimezonepython-datetime

How to add a timezone to a datetime object?


I have a variable which is grabbing a date object from a file. My aim is to add a timezone to this object so that it automatically changes the time based on the date its it then. So I expected it to add +1hour to it for dates in summertime (between march and october) and add +0hour in wintertime (between october and march).

 dt_object =  '20200901-01u30m30s'    
 dt_object = datetime.datetime.strptime(dt_object, '%Y%m%d-%Hu%Mm%Ss') 

 >>>print(dt_object) >>> 2020-09-01 01:30:30 
                             
 timezone= 'Europe/Amsterdam'
 dt_object_tz = pytz.utc.localize(dt_object).astimezone(pytz.timezone(timezone))        
 timeDiff = dt_object_tz.utcoffset().total_seconds()
 official_time = pytz.utc.localize(dt_object_tz+datetime.timedelta(seconds=timeDiff))

 >>>print(official_time) >>> 2020-09-01 03:30:30+00:00 
                             

As you can see this is a datetime object of september (so summertime!), I literally have no clue why it adds +2hours instead of 1 hour.... Can someone explain it and tell me what went wrong?

I just want my datetime object to be timezone-aware so it autmatically changes from summer to wintertime based on the date in grabs.


Solution

  • Regarding pytz, note that there is zoneinfo in the standard lib. No need for a third party library for time zone handling with Python >= 3.9. Example usage.


    Then, if your input represents wall time in some time zone, you can just localize. If the input represents UTC, you can set the tzinfo to UTC a bit more easily and then convert to local time using astimezone:

    from datetime import datetime, timezone
    import pytz
    
    s = '20200901-01u30m30s'    
    local_tz = 'Europe/Amsterdam'
    
    # if s represents local time, just localize:
    dtobj_tz = pytz.timezone(local_tz).localize(datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss'))
    # datetime.datetime(2020, 9, 1, 1, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
    
    # if s represents UTC, set it directly:
    dtobj_utc = datetime.strptime(s, '%Y%m%d-%Hu%Mm%Ss').replace(tzinfo=timezone.utc)
    # ...and convert to desired tz:
    dtobj_tz = dtobj_utc.astimezone(pytz.timezone(local_tz))
    # datetime.datetime(2020, 9, 1, 3, 30, 30, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)