Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the pytz library to obtain the corresponding local time when transitioning to or from Daylight Saving Time. Here's an example:

import datetime
import pytz

# set the time and timezone
dt = datetime.datetime(2021, 10, 31, 1, 30, tzinfo=pytz.timezone('US/Eastern'))

# get the time before DST transition
before_transition = dt - datetime.timedelta(minutes=30)

# get the time after DST transition
after_transition = dt + datetime.timedelta(minutes=30)

# convert to local time
local_before = before_transition.astimezone(pytz.timezone('US/Eastern'))
local_after = after_transition.astimezone(pytz.timezone('US/Eastern'))

print(local_before)
print(local_after)

In this example, we set the time to 1:30 AM Eastern Time on October 31, 2021, which is the day that DST ends in the United States. We then get the time 30 minutes before and after the DST transition and convert them to local time using the astimezone method. The output will show the corresponding local time for each of these times.