Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get timezone used by datetime.datetime.fromtimestamp()

Is it possible, and if yes, how, to get the time zone (i.e. the UTC offset or a datetime.timezone instance with that offset) that is used by datetime.datetime.fromtimestamp() to convert a POSIX timestamp (seconds since the epoch) to a datetime object?

datetime.datetime.fromtimestamp() converts a POSIX timestamp to a naive datetime object (i.e. without a tzinfo), but does so using the system's locale to adjust it to the local timezone and the UTC offset that was in effect at that time.

For example, using the date 2008-12-27 midnight UTC (40 * 356 * 86400 seconds since the epoch):

>>> datetime.datetime.fromtimestamp(40 * 356 * 86400) datetime.datetime(2008, 12, 27, 1, 0) 

That timestamp is converted to a datetime object at 1 o'clock in the morning (which it was at that time, here in an CET/CEST timezone). 100 days later, this is the result:

>>> datetime.datetime.fromtimestamp((40 * 356 + 100) * 86400) datetime.datetime(2009, 4, 6, 2, 0) 

Which is 2 o'clock in the morning. This is because by then, DST was active.

I'd expected that datetime.datetime.fromtimestamp() would set the tzinfo it uses in the returned datetime instance, but it doesn't.

like image 983
Feuermurmel Avatar asked Sep 15 '13 12:09

Feuermurmel


People also ask

How do I get the timezone from datetime?

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means. DateTimeOffset is somewhat better - that's basically a UTC time and an offset.

What timezone does datetime NOW () use?

In the documentation, it can also be seen that, since Python 3.6, datetime. now() can be called without any arguments and return the correct local result (naive datetime s are presumed to be in the local time zone).

Does Python datetime have timezone?

One of the modules that helps you work with date and time in Python is datetime . With the datetime module, you can get the current date and time, or the current date and time in a particular time zone.

Is datetime datetime NOW () UTC?

Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.


1 Answers

datetime.fromtimestamp(ts) converts "seconds since the epoch" to a naive datetime object that represents local time. tzinfo is always None in this case.

Local timezone may have had a different UTC offset in the past. On some systems that provide access to a historical timezone database, fromtimestamp() may take it into account.

To get the UTC offset used by fromtimestamp():

utc_offset = fromtimestamp(ts) - utcfromtimestamp(ts) 

See also, Getting computer's utc offset in Python.

like image 57
jfs Avatar answered Sep 20 '22 20:09

jfs