Check If Date is DayLight Saving in Python

This tutorial will discuss about a unique way to check if date is daylight saving in Python.

If you are working on an application that should handle users for different demographies, then you should handle the daylight properly.

Suppose you have a date along with the timezone information. Now you want to check if the given date is in daylight saving or not.

For this, we have created a method,

from datetime import datetime, timedelta, timezone
import pytz

def is_daylight_saving(date, tz):
    # Checks if a given date is in daylight saving time.
    # Returns True if the date is in daylight saving time, False otherwise.
    timezone = pytz.timezone(tz)
    date = timezone.localize(datetime.strptime(date, '%Y-%m-%d'))
    return date.dst() != timedelta(0)

It accepts a date and timezone as arguments, and check if the given date is in DayLight saving or not. It returns True, if the date is in DayLight saving, otherwise returns False.

In the first example we are going to test this method with a date that is in DayLight saving, and in second example we will test it with a date that is not in daylight saving.

Let’s see the complete example,

from datetime import datetime, timedelta, timezone
import pytz

def is_daylight_saving(date, tz):
    # Checks if a given date is in daylight saving time.
    # Returns True if the date is in daylight saving time, False otherwise.
    timezone = pytz.timezone(tz)
    date = timezone.localize(datetime.strptime(date, '%Y-%m-%d'))
    return date.dst() != timedelta(0)

# Example 1
date = '2022-06-01'
tz = 'US/Eastern'

if is_daylight_saving(date, tz):
    print('Yes, date is in DayLight Saving')
else:
    print('No, date is not in DayLight Saving')

# Example 2
date = '2022-12-01'
tz = 'US/Eastern'

if is_daylight_saving(date, tz):
    print('Yes, date is in DayLight Saving')
else:
    print('No, date is not in DayLight Saving')

Output

Yes, date is in DayLight Saving
No, date is not in DayLight Saving

Summary

We learned about a way to check if a Date is in DayLight Saving or not.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top