Alert a week before Daylight Savings in Python

Viewed 62

Background

I am trying to write code in Python that print's some message 7 days before Day light savings. In USA Daylight saving time in the United States is the practice of setting the clock forward by one hour when there is longer daylight during the dayIn the U.S., daylight saving time starts on the second Sunday in March and ends on the first Sunday in November

Solution So Far

from datetime import datetime   

def is_it_oct_31():
    today_date = datetime.today()
    return today_date.day == 31 and today_date.month == 10

def is_it_march_1():
    today_date = datetime.today()
    return today_date.day == 1 and today_date.month == 3


def check_if_it_is_daylight_saving():
    if is_it_oct_31():
        print("Time to set the clock 1 hour behind soon")
    if is_it_march_1():
        print("Time to set the clock 1 hour forward soon")

The idea behind my approach is simple, i try to check on dates that are few days before the day light saving event. However i am not sure if i can write code that would always alert me of a daylight saving event "7" days before the event. Any thoughts would be appreciated.

2 Answers

As far as I can see, your code has a fundamental flaw: it assumes that Daylight Saving occurs at the same date every year, which is not true. Looking at the Wikipedia Page, it starts at the 2nd Sunday in March and ends at the first Sunday in November.

If I were you, I would modify the two functions so as they take into account this aspect. And if you want to be alerted a week before Daylight Saving occurs, I think you need to leave the Python script running at startup. It checks what you want every time the computer is turned on.

Make a function that finds the nth Sunday of a month:

from datetime import datetime, timedelta

def get_sunday(month, nth):
    # First day of month
    month = datetime(datetime.today().year, month, 1)
    # Move to first Sunday (Sunday is 6th weekday)
    month += timedelta(days=6-month.weekday())
    # Move to nth Sunday
    month += timedelta(days=(nth-1)*7)
    # You can combine the last 2 lines as
    # month += timedelta(days=((nth-1)*7) + (6-month.weekday()))
    return month  

Then get DST start and end

dst_start = get_sunday(3, 2)
dst_end = get_sunday(11, 1)

Then calculate the number of days to each

days_until_dst_start = (dst_start - datetime.today()).days
days_until_dst_end = (dst_end - datetime.today()).days

And base your message on these values.

Related