Issue
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?
Solution
use the following to convert to a timestamp in python 2
int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))
Answered By - Richard Albright
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.