2017-12-26 2 views
0

사용자가 & 시간을 입력하면 시간대를 가져오고 싶습니다. 나는 중부 유럽에 살고 있으며 우리는 여기에 겨울 UTC + 001 및 여름 시간 UTC + 002 있습니다. 문제는, 나는 Python이 겨울과 여름에 항상 UTC + 002라는 여름 시간을 제공한다는 것을 테스트했습니다.시간대가 올바르지 않습니다.

예 :

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 
+0

문제점은 무엇입니까? 여름에는 +0200이며 지금 (12 월) +0100입니다 –

+0

다음은 잘못되었습니다. a는 여름, b는 겨울입니다. 출력 >>> '13:00:00 +0200 중부 유럽 서머 타임' time.strftime ("% H : % M : % S % z % Z" b) 출력 >>> '13 : 00 : 00 +0200 중부 유럽 서머 타임'# +0100은 중부 유럽 표준 시간이어야합니다. – Ahmad

답변

1

time.strftime('%z %Z', tuple)은 로컬 컴퓨터 현재을 사용하고있는 UTC 오프셋 및 시간대 약어 의 문자열 표현을 반환합니다. 튜플이 속한 시간대를 파악하려고하지는 않습니다.

이렇게하려면 일광 절약 시간제 경계를 찾고 특정 시간대에 대해 해당 utcoffsets을 찾아야합니다. 이 정보는 tz ("Olson") database에 있으며 파이썬에서는 대부분이 사람들이 을 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)) 

인쇄

13:00:00 +0200 CEST 
13:00:00 +0100 CET 
관련 문제