Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 datetime.timestamp in python2?

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?

like image 640
Niols Avatar asked May 04 '15 00:05

Niols


People also ask

What is T and Z in timestamp Python?

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).

How do I convert UTC timestamp to date in Python?

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.

What is Strftime and Strptime in Python?

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.


1 Answers

use the following to convert to a timestamp in python 2

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

like image 116
Richard Albright Avatar answered Oct 07 '22 00:10

Richard Albright