19

I am creating a date that is 10:30 today in New York:

from pytz import timezone
ny_tz = timezone('America/New_York')
ny_time = datetime(2014, 9, 4, 10, 30, 2, 294757, tzinfo=ny_tz)

This prints:

2014-09-04 10:30:02.294757-04:56

I am trying to compare this to another new york time which has the time zone offset 4:00 and so the comparison doesn't work.

How can I make the time zone offset 4:00 ?

1
  • 2
    In your code, what is timezone?
    – wwii
    Sep 4, 2014 at 14:52

1 Answer 1

28

You should instead do it like this:

ny_tz = timezone('America/New_York')
ny_time = ny_tz.localize(datetime(2014, 9, 4, 10, 30, 2, 294757))

This gives you the correct result:

>>> print ny_tz.localize(datetime(2014, 9, 4, 10, 30, 2, 294757))
2014-09-04 10:30:02.294757-04:00

Relevant pytz documentation section: http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

What happens in your case is timezone being blindly attached to the datetime object, without knowing its year, month, etc. Because the date is not known, and it is impossible to determine what was the time legislation at the moment, should DST be in effect, etc., it is assumed that you just want the geographical time for New York, which you get.

The results may vary for different years. For example, daylight saving time was introduced in the US in 1918, so the results for the same date in 1917 and 1918 differ:

>>> print ny_tz.localize(datetime(1917, 9, 4, 10, 30, 2, 294757))
1917-09-04 10:30:02.294757-05:00
>>> print ny_tz.localize(datetime(1918, 9, 4, 10, 30, 2, 294757))
1918-09-04 10:30:02.294757-04:00
2
  • 6
    this time zone stuff is not for the faint of heart!
    – Atma
    Sep 4, 2014 at 15:10
  • 1
    @Atma yeah that's true. I know many really smart and skilled programmers who have troubles with Python's timezone handling.
    – Spc_555
    Sep 4, 2014 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.