Search code examples
pythontimezonepytz

How do I combine a timezone aware date and time in Python?


I have a date and a time that I'm attempting to combine in Python. The time is timezone aware.

However, when I try and combine them, I get the wrong time.

import pytz
from datetime import time, date
NYC_TIME = pytz.timezone('America/New_York')

start_date = date(2012, 7, 7)
start_time = time(hour = 0, tzinfo = NYC_TIME)
combined = datetime.combine(start_date, start_time)
print combined
print NYC_TIME.normalize(combined)

This prints 2012-07-07 00:00:00-05:00, which normalizes to 2012-07-07 01:00:00-04:00. Why is this happening? How can I avoid it?


Solution

  • A time without a date attached must assume it's not in the Daylight Saving period. Once you attach a date to it, that assumption can be corrected. The zone offset changes, and the time changes as well to keep it at the same UTC equivalent.