Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 413
Chris B. Avatar asked Jun 28 '12 22:06

Chris B.


People also ask

How do you make a timezone aware datetime object in Python?

You can also use the pytz module to create timezone-aware objects. For this, we will store the current date and time in a new variable using the datetime. now() function of datetime module and then we will add the timezone using timezone function of pytz module.

How do I make datetime object aware?

The easiest way to tell if a datetime object is naive is by checking tzinfo. tzinfo will be set to None of the object is naive. To make a datetime object offset aware, you can use the pytz library. First, you have to instantiate a timezone object, and then use that timezone object to "localize" a datetime object.

How do you write timezone in Python?

Format UTC DateTime to Get the timezone name Extract the timezone name from UTC DateTime using the DateTime formatting in Python. Use the %Z directive to get the timezone name.


1 Answers

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.

like image 51
Mark Ransom Avatar answered Oct 06 '22 07:10

Mark Ransom