Search code examples
pythondatetimetimezonedstpytz

Python datetime conversions from one local timezone to another (+ bonus DST's)


I'm having some trouble understanding why I'm getting the results I'm getting.

What I wanted to try:

  1. Take two timezones, one that uses DST and one that doesn't. ex: Romania (dst) and Venezuela(no dst).

  2. For the timezone that has dst, create two datetimes. One in the interval of the dst, and one that isn't. Romania DST interval (4-10 / April-October). Ex:

    from datetime import datetime
    from pytz import timezone
    
    tz1 = timezone('Europe/Bucharest')
    tz2 = timezone('America/Caracas')
    
    date1 = datetime(2016, 5, 5, 5, 0, 0, tzinfo=tz1)  # its in the dst interval (5 o'clock, summer - dst)
    date1 = datetime(2016, 12, 5, 5, 0, 0, tzinfo=tz1)  # isn't in the dst interval (5 o'clock, winter - no dst)
    
    x = date1.astimezone(tz2)
    y = date2.astimezone(tz2) 
    
  3. Shouldn't x and y have different hours? Because date1 is in the DST interval, so 5 o'clock should mean a different hour than 5 o'clock in date2 when the datetime isn't in the DST interval.

Yet, both x and y have the same hour when converted to a no DST timezone.

Thanks for any explanations you can spare.


Solution

  • You can't use the datetime constructor to use a pytz timezone, you must use localize:

    date1 = tz1.localize(datetime(2016, 5, 5, 5, 0, 0))
    date2 = tz1.localize(datetime(2016, 12, 5, 5, 0, 0))
    

    From the documentation:

    Unfortunately using the tzinfo argument of the standard datetime constructors ‘‘does not work’’ with pytz for many timezones.