Ask Your Question
3

How can I obtain the corresponding local time in Python when transitioning to or from Daylight Saving Time?

asked 2022-10-21 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-29 17:00:00 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-21 11:00:00 +0000

Seen: 7 times

Last updated: Jul 29 '21