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?
The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time. The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Getting the UTC timestamp Use the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
use the following to convert to a timestamp in python 2
int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With