In Python, how do I convert a datetime.datetime into the kind of float that I would get from the time.time function?
57
votes
5 Answers
47
votes
14
votes
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()
10
votes
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.