我有一段python3代码,在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()该代码目前正在python3中运行。我希望它能在python2中工作。我唯一的问题来自以下几个方面:
first_run.timestamp()我试着用这样的东西来代替它:
(first_run - datetime(1970, 1, 1)).total_seconds()但是我的时区似乎有问题(UTC太容易了,我在UTC+2)。在first_run中应该有一些关于tzinfo的东西。也许我该加点什么?
我很迷茫,任何帮助都将不胜感激。提前谢谢你帮我。
EDIT1:
在吴浩辰发表评论后,我读到了将datetime转换为Unix时间戳并在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()不同。
也许是因为冬天/夏天的时间?
发布于 2015-05-04 00:52:31
使用以下方法将python 2中的时间戳转换为
int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))
发布于 2015-05-04 00:43:40
在time.time()中使用python2,它类似于python3中的datetime.timestamp()
如果您需要当前日期时间实现,请参见在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)
https://stackoverflow.com/questions/30020988
复制相似问题