CodexBloom - Programming Q&A Platform

Date Arithmetic in Python: implementing timedelta and DST Transitions

👀 Views: 34 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
python datetime pytz Python

I've been banging my head against this for hours. Could someone explain I'm deploying to production and I'm building a feature where I'm working with issues when performing date arithmetic in Python, especially around Daylight Saving Time (DST) transitions..... I have a date and time in UTC and I want to subtract a `timedelta` of 24 hours, but I'm noticing that sometimes the resulting time is off by an hour around the DST change. Here's a snippet of my code: ```python from datetime import datetime, timedelta import pytz # UTC date utc_date = pytz.utc.localize(datetime(2023, 3, 12, 12, 0, 0)) # Before DST starts in many areas # Subtracting 24 hours result = utc_date - timedelta(hours=24) print(result) ``` When I run this code, I expect the result to be March 11, 2023, at 12:00 UTC, but around the time of the DST transition, it gives me a different hour. I also tried using the `astimezone()` method to convert to a local timezone after the subtraction, but the results are still inconsistent: ```python local_tz = pytz.timezone('America/New_York') result_local = result.astimezone(local_tz) print(result_local) ``` This outputs an unexpected time, especially when I perform similar calculations around the fall transition. Are there best practices for handling these kinds of date calculations in Python? How can I ensure that my date arithmetic takes DST into account correctly? This is happening in both development and production on CentOS. Am I missing something obvious? Has anyone else encountered this? What's the best practice here?