python2中的python3 datetime.timestamp? [英] python3 datetime.timestamp in python2?

查看:77
本文介绍了python2中的python3 datetime.timestamp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段 python3 代码,它在 22:00 调用一个函数.

I have a piece of python3 code, that calls a function at 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 中工作.我唯一的问题来自以下几点:

This code is currently working in python3. I would like it to work in python2. My only problem comes from the following:

first_run.timestamp()

我尝试用以下内容替换它:

I tried to replace it with something like:

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

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

But there seems to be a problem with my timezone (UTC would be too easy, I'm in UTC+2). There should be something with tzinfo in first_run. Maybe I should add something?

我很迷茫,任何帮助将不胜感激.非常感谢您帮助我.

I'm quite lost, and any help would be appreciated. Thanks a lot by advance for helping me.

编辑 1:

在 Haochen Wu 的评论之后,我阅读了 将日期时间转换为 Unix 时间戳并在 python 中将其转换回

After Haochen Wu's comment, I've read Convert datetime to Unix timestamp and convert it back in python

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

Now I know that the following lines are equivalent for me:

(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()不同.

But this is not the case. This value is still different from mod_time.time().

也许是因为冬天/夏天的时间?

Maybe because of winter/summer hours?

推荐答案

在python 2中使用以下方法转换为时间戳

use the following to convert to a timestamp in python 2

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

这篇关于python2中的python3 datetime.timestamp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆