Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does python new york time zone display 4:56 instead 4:00?

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 ?

like image 466
Atma Avatar asked Sep 04 '14 14:09

Atma


People also ask

How does Python handle time zones?

So in order to work with the timezone smoothly, it is recommended to use the UTC as your base timezone. To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz.

How do I change the default timezone in Python?

to convert time between timezones, you could use pytz module e.g., tz = pytz. timezone('Europe/London'); london_time = tz. normalize(aware_dt. astimezone(tz)) .

What timezone does Python use?

Note: UTC – Coordinated Universal Time is the common time standard across the world. So, to work with the timezone without any issues, it is recommended to use the UTC as your base timezone.


1 Answers

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
like image 53
Spc_555 Avatar answered Oct 17 '22 20:10

Spc_555