0

I have code that I've put together to identify the exact hour the daylight savings time starts and when it ends. The problem is that I can't catch everything between those particular hours, on those dates, and say that yes it is within daylight savings time. My code for detecting the hours is as follows:

def getDaylightSavings(date, hourEnding):

    #  daylight saving's time switches
    #print date.month, date.isoweekday(), date.day, hourEnding
    if (date.month == 3 and date.isoweekday() == 7 and (date.day >= 8 and date.day <= 14) and hourEnding == 3): return 1
    if (date.month == 11 and date.isoweekday() == 7 and (date.day >= 1 and date.day <= 7) and hourEnding == 3): return 2

This way I know what time adjustments to use. The problem is that if the time I pass into the function is 3/11/2018 4:00:00 it won't return as daylight savings whereas 3/11/2018 3:00:00 will be detected.

Is there a library I can use for determining daylight savings or something I can do here code-wise that will help?

This question is not a duplicate because I need to determine whether daylight savings time is in effect for any arbitrary time. Please help.

Ravaal
  • 3,233
  • 6
  • 39
  • 66
  • You want the `pytz` library. – thebjorn Aug 21 '18 at 18:57
  • `pytz` is in utc. The comment above about using the `time` module seems promising but the problem is that it's not clear how I can use it for a datetime like `u'2018-04-29T23:00:00'` – Ravaal Aug 21 '18 at 18:58
  • ahh, the perks of working with times.. – DeepSpace Aug 21 '18 at 19:04
  • A time string like `u'2018-04-29T23:00:00'` should be treated with caution. It has no timezone info, so you need to be certain about whether it's a local time, or a UTC time. And if it's local, make sure it's from your locality. ;) – PM 2Ring Aug 21 '18 at 19:10
  • You may find jfs's answer here to be what you need: https://stackoverflow.com/a/19968515/4014959 He has a version that only uses stdlib modules. Unfortunately, it only tells you if DST is in effect now, not at an arbitrary time. – PM 2Ring Aug 21 '18 at 19:12
  • That's not what I need. I need to determine whether daylight savings time is in effect or not. – Ravaal Aug 22 '18 at 13:58
  • When you have a datetime like that without any other meta information *you are screwed*, in the same way as when you try to open a text file without knowing its encoding. You can take some guesses, but you can be wrong. – Giacomo Alzetta Aug 22 '18 at 15:30
  • I don’t see why this is any different from those other questions. You take a time zone and a `datetime`, call the `.dst()` method and you have your answer. – Dietrich Epp Aug 22 '18 at 15:36
  • If you can make it happen then by all means post an answer... it's not that easy. – Ravaal Aug 23 '18 at 13:37

0 Answers0