How to convert datetime to time float (unix timestamp) in Python 2

Use this snippet to convert a datetime.datetime object into a float (like the one time.time() returns) in Python 2.x:

from datetime import datetime
import time

dt = datetime.now()
timestamp = time.mktime(dt.timetuple()) + dt.microsecond/1e6

After running this, timestamp will be 1563812373.1795 for example.

or use this function:

from datetime import datetime
import time

def datetime_to_timestamp(dt):
    return time.mktime(dt.timetuple()) + dt.microsecond/1e6

In Python 3, you can simply use

dt.timestamp()

but that is not supported in Python 2.