Calculate tm_isdst from date and time

When 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 structure for me, but the tm_isdst flag tm_isdst incorrect. In early June, DST was active, but no matter what date I enter the tm_isdst flag, it is always set to what is in localtime() right now. I need to know if the DST was active or not on the input date.

0
python timezone time
Nov 19
source share
2 answers

First of all, do not include time.strftime('%Z') in your format. You say that your current clockwise offset (including daylight saving time is turned off), and that is [possible], using this to set tm_isdst.

Without this, you should get a structure 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 this to mktime, which, given the value -1 , will “guess” the DST value (I put “guess” in quotation marks because it will always be correct, except for the 2AM ambiguous 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 the DST flag set correctly:

 >>> time.localtime(1338566400).tm_isdst 1 

You can also skip the strptime step and pass the values ​​directly to mktime:

 >>> time.mktime((2012,6,1,12,0,0,-1,-1,-1)) 1338566400.0 
+2
Nov 19 '12 at 13:26
source share

Your question is equivalent to how to convert the local time, indicated as a string, into local time with the local time zone information attached:

 from datetime import datetime from pytz.exceptions import InvalidTimeError # $ pip install pytz from tzlocal import get_localzone # $ pip install tzlocal naive_dt = datetime.strptime("2012-06-01 12:00:00", "%Y-%m-%d %H:%M:%S") local_tz = get_localzone() try: local_dt = local_tz.localize(naive_dt, is_dst=None) except InvalidTimeError as e: print("can't determine whether DST is active, reason: %s" % (e,)) else: assert local_dt.dst() is not None print("DST is %sactive" % ("" if local_dt.dst() else "not ",)) 

It uses the Olson tz database ( pytz module) and therefore:

  • it works for past dates when the UTC offset could be different for reasons not related to the DST.
  • it detects ambiguous or non-existent local times when the DST cannot be determined
  • it works on Windows and * nix ( tzlocal module)

Note: mktime() solution shown in @ Random832's answer :

 import time isdst = time.localtime(time.mktime(naive_dt.timetuple())).tm_isdst > 0 
  • it may give the wrong result silently for a date in the past if the OS does not provide its own chronological time database
  • it may produce the wrong result silently for ambiguous or non-existent local times (during DST transition)
0
Apr 17 '14 at 17:01
source share



All Articles