Why is the timezone displayed in python new york 4:56 instead of 4:00?

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

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

      

Prints:

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

I am trying to compare this to another new york time that has a timezone offset of 4:00 and so the comparison does not work.

How do I make the timezone offset 4:00?

+3


source to share


1 answer


You should 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 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

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

What happens in your case is a timezone that is blindly tied to a datetime object without knowing its year, month, etc. Since the date is unknown and it is not possible to determine what the time was at that time by law, DST, etc., it is assumed that you just want the geographic time for New York that you are getting.

Results may vary from year to year. For example, daylight saving time was introduced in the United States in 1918, so the results for the same date in 1917 and 1918 are different:

>>> 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

      

+8


source







All Articles