将unixtime转换为datetime对象并再次转换(一对时间转换函数是逆函数)

2024-03-29 00:36:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一对函数dtut,它们在正常的unix时间(1970-01-01 00:00:00 UTC之后的秒数)和Python datetime对象之间来回转换。

如果dtut是正确的倒数,则此代码将打印相同的时间戳两次:

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))

唉,第二个时间戳比第一个时间戳少3600秒(一小时)。 我认为这种情况只发生在非常特殊的时间段,可能是在夏令时跳过的那个时间段。 但是有没有办法写dtut所以它们是彼此的真逆?

相关问题:Making matplotlib's date2num and num2date perfect inverses


Tags: and对象函数datetimereturntimedef时间
1条回答
网友
1楼 · 发布于 2024-03-29 00:36:11

你是对的,这种行为与夏令时有关。避免这种情况的最简单方法是确保您使用的时区没有夏令时,UTC在这里最有意义。

^{}^{}处理UTC时间,并且是精确的逆。

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())

以下是文档中关于^{}夏令时问题背后的一些解释:

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.

这里的重要部分是,您得到一个天真的datetime.datetime对象,这意味着没有时区(或日光节约)信息作为对象的一部分。这意味着使用fromtimestamp()时,多个不同的时间戳可以映射到相同的datetime.datetime对象,如果您碰巧选择了夏时制回滚期间的时间:

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

相关问题 更多 >