60

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

Ram Rachum
  • 84,019
  • 84
  • 236
  • 374
  • related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/a/8778548/4279) – jfs Feb 09 '16 at 04:29

5 Answers5

51

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
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • 1
    Can you explain why this solution is better than `(dt - datetime.datetime.utcfromtimestamp(0)).total_seconds()`? The manual addition of microseconds seems inelegant to me. – Ram Rachum Nov 05 '11 at 21:57
  • 4
    @RamRachum: your formula assumes that `dt` is UTC time. `mktime()` assumes that the input is local time. You should avoid using naive datetime objects that represent local time unless you want to display them immediately. Use UTC time or timezone-aware datetime objects instead. – jfs Feb 09 '16 at 04:29
34
time.mktime(dt_obj.timetuple())

Should do the trick.

Amber
  • 507,862
  • 82
  • 626
  • 550
17

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()
lsowen
  • 3,728
  • 1
  • 21
  • 23
  • 3
    `timestamp = time.time()` – jfs Feb 09 '16 at 04:26
  • That would handle this specific case (find current timestamp), but using ``datetime.timestamp()`` is more powerful because it allows you to find the timestamp at an arbitrary datetime. – lsowen Mar 01 '16 at 16:12
  • 4
    Provide a better example then. Because `.now().timestamp()` is strictly worse than `time.time()`. The former may produce a wrong result during DST transitions. A better example: `.now(utc).timestamp()` (at least, it produces the right result). – jfs Mar 01 '16 at 16:19
10

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    `((24*3600*td.days + td.seconds)*1000000 + td.microseconds)/1e6` on Python <2.7 – jfs Nov 05 '11 at 18:54
7

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

>>> import datetime
>>> import time
>>> now = datetime.datetime.now()
>>> secondsSinceEpoch = time.mktime(now.timetuple())
bgporter
  • 35,114
  • 8
  • 59
  • 65