CodexBloom - Programming Q&A Platform

Confusion with Python 2.7's `datetime` and timezone handling leading to incorrect calculations

πŸ‘€ Views: 82 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-21
python-2.7 datetime timezone pytz Python

I'm reviewing some code and I'm sure I'm missing something obvious here, but I tried several approaches but none seem to work. I'm encountering an issue with handling timezones in Python 2.7 using the `datetime` module. I have the following code to convert a naive datetime to an aware datetime, but the output isn't what I expect: ```python from datetime import datetime, timedelta, tzinfo import pytz # Create a naive datetime object naive_dt = datetime(2023, 10, 1, 12, 0) # Define the timezone (UTC+3) uat_tz = pytz.timezone('Europe/Moscow') # Convert naive to aware datetime aware_dt = uat_tz.localize(naive_dt) # Now, subtract 3 hours from this datetime new_dt = aware_dt - timedelta(hours=3) print('New datetime:', new_dt) ``` When I run this code, I expect to see the output reflecting the new time in the timezone of Europe/Moscow. However, the output shows the time without properly adjusting for daylight saving time, which causes the result to be incorrect. The output I get is: ``` New datetime: 2023-10-01 09:00:00+03:00 ``` Given that October is a month where daylight saving time may impact the actual hour offset, I was expecting the adjusted time to reflect this. I have also tried using `normalize` after the subtraction: ```python new_dt = uat_tz.normalize(aware_dt - timedelta(hours=3)) ``` But this still doesn’t provide the correct output. I have installed the `pytz` library (version 2019.1), so I believe I am using the correct timezone definitions. What am I missing here? Is there a different best practice for handling timezone adjustments in this case? Any insights would be greatly appreciated! Any help would be greatly appreciated! For context: I'm using Python on Windows. Is there a better approach? Any ideas what could be causing this? This is for a service running on Debian. Cheers for any assistance!