5

I need help solving this problem with Python 3. I need to know is given date, for example 2017 06 02, is in Daylight Saving Time period or not.

I was looking for an answer here and on google. But what I found is basically solving this problem only with current date. And to modify those examples to my needs it's just too difficult for me :/ Unfortunately I'm not that efficient with Python yet.

Perfect solution would be just getting true of false as an answer. Then I would be able to proceed with my logic.

Edit: As I said I found some solutions here. But they all are solving this problem with current time. I need to know if some date from the future or past is in Daylight Saving Time period. Problem is that I'm a junior and to modify those examples I found to my needs is too difficult for me.

Simon Lickus
  • 173
  • 2
  • 8
  • 1
    Possible duplicate of [Python daylight savings time](http://stackoverflow.com/questions/2881025/python-daylight-savings-time) – techydesigner Sep 21 '16 at 08:15
  • There will be one (and likely two if the transition time is not midnight) days per year where knowing the date does not give enough evidence to determine whether it's daylight savings time. Additionally on the day that you fall back there will be one hour in that day that knowing the local time will not tell you whether day light savings time is in effect. – Steven Rumbalski Sep 21 '16 at 13:52
  • For this reason you should use [`pytz`](http://pytz.sourceforge.net/) and follow their advice that "the preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans." – Steven Rumbalski Sep 21 '16 at 13:55

2 Answers2

6

Ok, I think I managed to do this by myself. First I wrote this function:

import time

def is_dst(date):
    return bool(time.localtime(date).tm_isdst)

Next I got true or false like this:

is_dst(time.mktime(MyDateObject.timetuple())))

I am sure that this is not the best solution as I am a total Python noob, but it is working for me. So now from this point I can move on with my logic.

Simon Lickus
  • 173
  • 2
  • 8
  • `bool(time.localtime(MyDateObject.timestamp()).tm_isdst)` is shorter and also about 4 times faster on my machine (Python 3.8 x86_64). – Cristian Ciupitu Oct 29 '20 at 10:26
3
import time # imports the time module
time.localtime().tm_isdst # localtime() returns a tuple

Value is 0 when DST is not in effect.

Value is 1 when DST is in effect.

Value is -1 when DST is unknow.

techydesigner
  • 1,681
  • 2
  • 19
  • 28