从日期和时区计算 tm_isdst [英] Calculate tm_isdst from date and timezone
问题描述
当我跑线时
time.strptime("2012-06-01 12:00:00 "+time.strftime("%Z"), "%Y-%m-%d %H:%M:%S%Z")
它为我创建了一个结构,但标志 tm_isdst
是错误的.6 月初 DST 处于活动状态,但无论我输入什么日期,tm_isdst
标志始终设置为它现在在 localtime()
中的值.我需要知道 DST 在我输入的日期是否有效.
首先,不要在你的格式中包含 time.strftime('%Z')
.您告诉它您当前的 GMT 偏移量(包括关闭夏令时),并且 [可能] 使用它来设置 tm_isdst.
没有它,你应该得到一个带有 tm_isdst=-1
的结构:
现在,您可以将它传递给 mktime,它会在给定 -1
值的情况下猜测"DST 值(我将猜测"放在引号中,因为它总是正确的,除了模棱两可的凌晨 2 点案例).这将以 time()
格式给出绝对时间.
然后你可以用这个值调用localtime,它会有一个正确设置的DST标志:
<预><代码>>>>time.localtime(1338566400).tm_isdst1您也可以跳过 strptime 步骤,直接将值传递给 mktime:
<预><代码>>>>time.mktime((2012,6,1,12,0,0,-1,-1,-1))1338566400.0When I run the line
time.strptime("2012-06-01 12:00:00 "+time.strftime("%Z"), "%Y-%m-%d %H:%M:%S %Z")
it creates a struct for me but the flag tm_isdst
is wrong. At the first of June DST was active but no matter what date I enter the tm_isdst
flag is always set to what it is in localtime()
right now. I need to know if DST was active or not on the date I enter.
First of all, don't include time.strftime('%Z')
in your format. You're telling it your current GMT offset (including daylight saving being off) and it's [probably] using that to set tm_isdst.
Without that, you should get a struct with tm_isdst=-1
:
>>> time1 = time.strptime("2012-06-01 12:00:00", "%Y-%m-%d %H:%M:%S")
>>> time1
time.struct_time(tm_year=2012, tm_mon=6, tm_mday=1, tm_hour=12, tm_min=0,
tm_sec=0, tm_wday=4, tm_yday=153, tm_isdst=-1)
Now, you can pass that to mktime, which will, given the -1
value, "guess" the DST value (I put "guess" in quotes because it will always be correct except for ambiguous 2AM cases). This will give the absolute time in time()
format.
>>> time.mktime([previous value]) # my timezone is US Eastern
1338566400.0
Then you can call localtime with this value, and it will have a correctly set DST flag:
>>> time.localtime(1338566400).tm_isdst
1
You can also skip the strptime step and directly pass the values to mktime:
>>> time.mktime((2012,6,1,12,0,0,-1,-1,-1))
1338566400.0
这篇关于从日期和时区计算 tm_isdst的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!