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
467 views
in Technique[技术] by (71.8m points)

python - Convert a unixtime to a datetime object and back again (pair of time conversion functions that are inverses)

I'm trying to write a pair of functions, dt and ut, that convert back and forth between normal unix time (seconds since 1970-01-01 00:00:00 UTC) and a Python datetime object.

If dt and ut were proper inverses then this code would print the same timestamp twice:

import time, datetime

# Convert a unix time u to a datetime object d, and vice versa
def dt(u): return datetime.datetime.fromtimestamp(u)
def ut(d): return time.mktime(d.timetuple())

u = 1004260000
print u, "-->", ut(dt(u))

Alas, the second timestamp is 3600 seconds (an hour) less than the first. I think this only happens for very particular unixtimes, maybe during that hour that daylight savings time skips over. But is there a way to write dt and ut so they're true inverses of each other?

Related question: Making matplotlib's date2num and num2date perfect inverses

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You are correct that this behavior is related to daylight savings time. The easiest way to avoid this is to ensure you use a time zone without daylight savings, UTC makes the most sense here.

datetime.datetime.utcfromtimestamp() and calendar.timegm() deal with UTC times, and are exact inverses.

import calendar, datetime

# Convert a unix time u to a datetime object d, and vice versa
def dt(u): return datetime.datetime.utcfromtimestamp(u)
def ut(d): return calendar.timegm(d.timetuple())

Here is a bit of explanation behind why datetime.datetime.fromtimestamp() has an issue with daylight savings time, from the docs:

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

The important part here is that you get a naive datetime.datetime object, which means there is no timezone (or daylight savings) information as a part of the object. This means that multiple distinct timestamps can map to the same datetime.datetime object when using fromtimestamp(), if you happen to pick times that fall during the daylight savings time roll back:

>>> datetime.datetime.fromtimestamp(1004260000) 
datetime.datetime(2001, 10, 28, 1, 6, 40)
>>> datetime.datetime.fromtimestamp(1004256400)
datetime.datetime(2001, 10, 28, 1, 6, 40)

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

...