在python中将datetime.date优化为unix时间戳转换

问题描述 投票:0回答:1

我一直在尝试尽快执行此操作,同时还避免了时区问题。

此方法似乎是最慢的:

def to_unix_timestamp(stamp):
    return int(stamp.strftime('%s'))

它产生以下结果:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
4328301    1.620    0.000   10.009    0.000 utils.py:13(to_unix_timestamp)

这似乎好一些,但按照我的喜好仍然相对较慢:

def to_unix_timestamp(stamp):
    return time.mktime(stamp.timetuple())

结果:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
4328301    1.381    0.000    8.158    0.000 utils.py:13(to_unix_timestamp)

我有什么办法可以在不干扰时区的情况下实现大幅提速?请注意,我仅限于python 2.7。

python python-2.7 optimization unix-timestamp
1个回答
0
投票

定义d0 = datetime.date(1970, 1, 1),然后执行(stamp - d0).total_seconds()? …–杰森哈珀

我遇到了我担心的“时区”问题。在针对其他方法进行验证后,我发现来自该方法的时间向前偏移了一个小时。知道是什么原因造成的吗?

是,其他方法隐式使用本地时间,说明了您的时区。 datetime.date对象d0(具有1天的分辨率)不携带该时区信息,因此,取差stamp - d0时会出现差异。为了解决这个问题,我们可以构造一个代表真正时期的d0

d0 = datetime.datetime.fromtimestamp(0)

因此,(datetime.datetime.combine(stamp, datetime.time.min) - d0).total_seconds()会产生您期望的值。

© www.soinside.com 2019 - 2024. All rights reserved.