【发布时间】:2015-07-13 07:10:47
【问题描述】:
我有一段 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 的内容。也许我应该添加一些东西?
我很迷茫,任何帮助将不胜感激。 非常感谢您帮助我。
编辑1:
经过吴昊辰的评论,我看了Convert datetime to Unix timestamp and convert it back in 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()不同。
也许是因为冬/夏时间?
【问题讨论】:
-
我刚刚读过它。现在我知道
(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()。也许是因为冬/夏时间? -
我最好的猜测是您需要实现 tzinfo 的子类并将其添加到 datetime 对象中。请参阅文档:docs.python.org/2/library/datetime.html#tzinfo-objects
-
dateutil 中似乎有一些帮助功能。你可以使用额外的包吗?
-
如果可能,我想避免使用额外的包(例如在 pypi 上似乎不是最新的 dateutils)。但考虑到这至少是我第三次遇到使用 dateutils 的优势,我可能会使用它……
标签: python python-3.x python-2.x