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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With