Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...