Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timezone conversion in Python

I'm probably missing something about timezones:

>>> import datetime, pytz
>>> date = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.timezone("Europe/Paris"))
>>> date.astimezone(pytz.UTC)
datetime.datetime(2013, 9, 3, 15, 51, tzinfo=<UTC>)

I was expecting

datetime.datetime(2013, 9, 3, 15, 00, tzinfo=<UTC>)

Can anyone explain me where these 51 minutes come from?

Thanks,

Jean-Philippe

like image 448
jmague Avatar asked Nov 12 '13 14:11

jmague


People also ask

How do I convert between time zones in Python?

Converting Between TimezonesUse the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.

How do you convert timezone to UTC in Python?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.

How do I convert time to number in Python?

strftime() object. In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function. Returns : It returns the string representation of the date or time object.

Which Python library is used for timezone?

The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.


2 Answers

The UTC offset gives (date.tzinfo.utcoffset(date)):

datetime.timedelta(0, 540)

This is 540 seconds or 9 minutes.

In France the switch to UTC was made on March 11, 1911 and the clocks were turned back 9 minutes and 21 seconds (source 1, source 2):

Until 1911, Paris was 9 minutes and 21 seconds off UTC.

You can also see it here (Paris time in 1911) where the time goes from March 11, 12:01:00 AM to March 10, 11:51:39 PM.

like image 102
Simeon Visser Avatar answered Oct 31 '22 09:10

Simeon Visser


Read the note at the very begining of pytz documentation ; use .localize() method to create timezone-aware datetime object:

import datetime
import pytz

naive_dt = datetime.datetime(2013,9,3,16,0)
dt = pytz.timezone("Europe/Paris").localize(naive_dt, is_dst=None)

to_s = lambda d: d.strftime('%Y-%m-%d %H:%M:%S %Z%z')
print(to_s(dt))
print(to_s(dt.astimezone(pytz.utc)))

Output

2013-09-03 16:00:00 CEST+0200
2013-09-03 14:00:00 UTC+0000

I don't know why you are expecting 15:00 UTC here.

like image 35
jfs Avatar answered Oct 31 '22 08:10

jfs