问题
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()
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()
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.
EDIT1:
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()
The solution should be
(datetime.now() - datetime.fromtimestamp(0)).total_seconds()
But this is not the case. This value is still different from mod_time.time()
.
Maybe because of winter/summer hours?
回答1:
use the following to convert to a timestamp in python 2
int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))
回答2:
use time.time()
in python2, it's analog to datetime.timestamp()
in python3
datetime.datetime.timestamp
IF you need for current datetime realization, see implementation of that in 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()
where _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
来源:https://stackoverflow.com/questions/30020988/python3-datetime-timestamp-in-python2