Python: Converting from `datetime.datetime` to `time.time`

PythonTimeCalendar

Python Problem Overview


In Python, how do I convert a datetime.datetime into the kind of float that I would get from the time.time function?

Python Solutions


Solution 1 - Python

It's not hard to use the time tuple method and still retain the microseconds:

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2011, 11, 5, 11, 26, 15, 37496)

>>> time.mktime(t.timetuple()) + t.microsecond / 1E6
1320517575.037496

Solution 2 - Python

time.mktime(dt_obj.timetuple())

Should do the trick.

Solution 3 - Python

I know this is an old question, but in python 3.3+ there is now an easier way to do this using the datetime.timestamp() method:

from datetime import datetime
timestamp = datetime.now().timestamp()

Solution 4 - Python

Given a datetime.datetime object dt, you could use

(dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()

Example:

>>> dt = datetime.datetime.now(); t = time.time()
>>> t
1320516581.727343
>>> (dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()
1320516581.727296

Note that the timedelta.total_seconds() method was introduced in Python 2.7.

Solution 5 - Python

A combination of datetime.timetuple() and time.mktime():

>>> import datetime
>>> import time
>>> now = datetime.datetime.now()
>>> secondsSinceEpoch = time.mktime(now.timetuple())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRam RachumView Question on Stackoverflow
Solution 1 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 2 - PythonAmberView Answer on Stackoverflow
Solution 3 - PythonlsowenView Answer on Stackoverflow
Solution 4 - PythonSven MarnachView Answer on Stackoverflow
Solution 5 - PythonbgporterView Answer on Stackoverflow