Ahmad
Ahmad

Reputation: 227

Time zone is not correct

I want to get the time zone when a user enters the date & time. I am living in middle europe and we have here in winter UTC+001 and summer time UTC+002. The problem is, I've tested that python, for winter and summer, always gives the summer time UTC+002.

Example:

import time

a=time.strptime("13 00 00 30 May 2017", "%H %M %S %d %b %Y")
a_s = time.mktime(a) # to convert in seconds
time.localtime(a_s) #local time
Output>>> time.struct_time(tm_year=2017, tm_mon=5, tm_mday=30, tm_hour=13, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=150, tm_isdst=1)

time.gmtime(a_s) # UTC time
Output>>> time.struct_time(tm_year=2017, tm_mon=5, tm_mday=30, tm_hour=11, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=150, tm_isdst=0)

#Now the Winter
b = time.strptime("13 00 00 20 Dec 2017", "%H %M %S %d %b %Y")
b_s = time.mktime(b)
time.localtime(b_s)
Output>>> time.struct_time(tm_year=2017, tm_mon=12, tm_mday=20, tm_hour=13, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=354, tm_isdst=0)

time.gmtime(b_s)
Output>>>time.struct_time(tm_year=2017, tm_mon=12, tm_mday=20, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=354, tm_isdst=0)

time.strftime("%H:%M:%S %z %Z",a)
Output>>>'13:00:00 +0200 Central European Summer Time'

time.strftime("%H:%M:%S %z %Z",b)
Output>>> '13:00:00 +0200 Central European Summer Time' #Wrong should be +0100 and Central European Time

Upvotes: 1

Views: 593

Answers (1)

unutbu
unutbu

Reputation: 879481

time.strftime('%z %Z', tuple) returns a string representation of the UTC offset and timezone abbreviation that your local machine is currently using. It does not try to figure out what timezone the tuple belongs to.

To do that requires looking up daylight savings time boundaries and the corresponding utcoffsets for a given timezone. This information is in the tz ("Olson") database and in Python most people delegate this job to the pytz module.

import time
import datetime as DT
import pytz
FMT = "%H:%M:%S %z %Z"

tz = pytz.timezone('Europe/Berlin')
for datestring in ["13 00 00 30 May 2017", "13 00 00 20 Dec 2017"]:
    a = time.strptime(datestring, "%H %M %S %d %b %Y")
    a_s = time.mktime(a)  
    # naive datetimes are not associated to a timezone
    naive_date = DT.datetime.fromtimestamp(a_s)
    # use `tz.localize` to make naive datetimes "timezone aware"
    timezone_aware_date = tz.localize(date, is_dst=None)
    print(timezone_aware_date.strftime(FMT))

prints

13:00:00 +0200 CEST
13:00:00 +0100 CET

Upvotes: 1

Related Questions