Nio*_*ols 14 python python-2.x python-3.x
我有一段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()
Run Code Online (Sandbox Code Playgroud)
此代码目前在python 3中工作.我希望它能在python 2中运行.我唯一的问题来自以下方面:
first_run.timestamp()
Run Code Online (Sandbox Code Playgroud)
我尝试用以下内容替换它:
(first_run - datetime(1970, 1, 1)).total_seconds()
Run Code Online (Sandbox Code Playgroud)
但是我的时区似乎有问题(UTC太容易了,我在UTC + 2).first_run中应该有tzinfo.也许我应该添加一些东西?
我很失落,任何帮助都会受到赞赏.非常感谢提前帮助我.
EDIT1:
在Haochen Wu的评论之后,我已经阅读了将datetime转换为Unix时间戳并将其转换回python中
现在我知道以下几行对我来说是等价的:
(datetime.now() - datetime(1970, 1, 1)).total_seconds()
(datetime.now() - datetime.utcfromtimestamp(0)).total_seconds()
Run Code Online (Sandbox Code Playgroud)
解决方案应该是
(datetime.now() - datetime.fromtimestamp(0)).total_seconds()
Run Code Online (Sandbox Code Playgroud)
但这种情况并非如此.这个值仍然不同于mod_time.time().
也许是因为冬季/夏季?
time.time()在python2中使用,它类似于datetime.timestamp()在python3中
如果您需要当前的日期时间实现,请参阅 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()
Run Code Online (Sandbox Code Playgroud)
其中 _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
使用以下内容将其转换为python 2中的时间戳
int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))