python3 datetime.timestamp in python2?



我有一块Python 3 代码,该代码在22:00调用函数。

# Imports
from datetime import datetime, date, time, timedelta
import sched
import time as mod_time
# Find the next datetime corresponding to 22:00
first_run = datetime.combine(date.today(), time(22,0))
first_run = first_run if first_run > datetime.now() else first_run + timedelta(1)
# Dumb test function
def my_function():
    print('my_function')
# Run the function at 22:00
scheduler = sched.scheduler(mod_time.time, mod_time.sleep)
scheduler.enterabs(first_run.timestamp(), 1, my_function, ())
scheduler.run()

此代码当前在Python中工作 3 。我希望它可以在Python 2 中工作。我唯一的问题来自以下内容:

first_run.timestamp()

我试图将其替换为:

(first_run - datetime(1970, 1, 1)).total_seconds()

但是我的时区似乎有问题(UTC太容易了,我在UTC 2中)。first_run中应该有tzinfo的东西。也许我应该添加一些东西?

我已经迷路了,任何帮助都将不胜感激。非常感谢Advance帮助我。

edit1:

在Haochen Wu的评论之后,我已将DateTime转换为UNIX TIMESTAMP,然后在Python中转换为

现在我知道以下几行对我来说是等效的:

(datetime.now() - datetime(1970, 1, 1)).total_seconds()
(datetime.now() - datetime.utcfromtimestamp(0)).total_seconds()

解决方案应为

(datetime.now() - datetime.fromtimestamp(0)).total_seconds()

但事实并非如此。此值仍然不同于mod_time.time()

也许是由于冬季/夏季?

使用以下内容转换为Python 2

中的时间戳

int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))

在python2中使用 time.time(),它与python3中的 datetime.timestamp()类似于python3

dateTime.dateTime.timestamp

如果您需要当前的DateTime实现,请参见Python3中的实现:

def timestamp(self):
    "Return POSIX timestamp as float"
    if self._tzinfo is None:
        return _time.mktime((self.year, self.month, self.day,
                             self.hour, self.minute, self.second,
                             -1, -1, -1)) + self.microsecond / 1e6
    else:
        return (self - _EPOCH).total_seconds()

其中_epoch = dateTime(1970,1,1,tzinfo = timezone.utc)

最新更新