Search code examples
pythondatetimetimezonedst

How to get the UTC + x number, according to local timezone and daylight saving?


How to get the UTC + x number, according to local timezone and daylight saving?

Example: let's say we're in Paris/France timezone. For a winter datetime (January 1st, 00:55:23), we expect 0001:

import datetime
print datetime.datetime(2018, 01, 01, 00, 55, 23).strftime('%z') 
# empty string because the datetime is naive
# expecting 0001

For a summer datetime, we expect 0002:

print datetime.datetime(2018, 07, 01, 00, 55, 23).strftime('%z') 
# expecting 0002

Solution

  • Using dateutil:

    from dateutil import tz
    from datetime import datetime
    
    paris = tz.gettz('Europe/Paris')
    
    dt1 = datetime(2018, 1, 1, 0, 55, 23, tzinfo=paris)
    dt2 = datetime(2018, 7, 1, 0, 55, 23, tzinfo=paris)
    
    print(dt1.strftime('%z'))  # prints +0100
    print(dt2.strftime('%z'))  # prints +0200
    

    Alternatively, using pytz:

    from pytz import timezone
    from datetime import datetime
    
    paris = timezone('Europe/Paris')
    
    dt1 = paris.localize(datetime(2018, 1, 1, 0, 55, 23))
    dt2 = paris.localize(datetime(2018, 7, 1, 0, 55, 23))
    
    print(dt1.strftime('%z'))  # prints +0100
    print(dt2.strftime('%z'))  # prints +0200