2017-12-26 55 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 +200中央ヨーロッパ夏時間' 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にあり、Pythonではほとんどの人が を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 
関連する問題