4

How can I produce a timestamp to millisecond accuracy from a date or datetime in Python?

There are an overwhelming number of methods and ways of doing this, and I'm wondering which is the most Pythonic way.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
Humphrey Bogart
  • 7,423
  • 14
  • 52
  • 59

3 Answers3

11

The following has worked for my purposes:

To datetime from millisecond timestamp

import datetime
timestamp #=> 1317912250955
dt = datetime.datetime.fromtimestamp(time/1000.0)
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)

From datetime to millisecond timestamp

import time
dt #=> datetime.datetime(2011, 10, 6, 10, 44, 10, 955000)
timestamp = int((time.mktime(dt.timetuple()) + dt.microsecond/1000000.0)*1000)
timestamp #=> 1317912250955
Shock3nAw
  • 121
  • 1
  • 6
2

date objects in Python don't preserve the notion of wallclock time. If you wanted to take a date object and get a representation with the millisecond, it would be all 0s.

The datetime module skips milliseconds and supports microseconds in its formatting. So when you print a datetime or see one in the interpreter, that last field is microsecond. If you want milliseconds, you can divide that field by 1000.

Here's a couple of examples from a Python 3.2b2 interpreter session. There's some extra stuff in here so you can see the basic route I took to get to a timestamp. It's not to be considered a substitute for reading the docs:

>>> x = datetime.datetime.today()
>>> y = datetime.date.today()
>>> x
datetime.datetime(2011, 2, 6, 8, 2, 9, 465714)
>>> y
datetime.date(2011, 2, 6)
>>> y.strftime('%Y-%m-%d.%f')
'2011-02-06.000000'
>>> x
datetime.datetime(2011, 2, 6, 8, 2, 9, 465714)
>>> str(x)
'2011-02-06 08:02:09.465714'
>>> x.microsecond
465714
>>> x.time()
datetime.time(8, 2, 9, 465714)
>>> x.time().microsecond/1000
465.714   # milliseconds and microseconds.
>>> int(x.time().microsecond / 1000)
465  # milliseconds
>>> s = '{:02d}:{:02d}:{:02d}.{:3d}'.format(r.hour, r.minute, r.second, int(r.microsecond / 1000), '2s')
>>> s
'08:02:09.465'
jonesy
  • 3,502
  • 17
  • 23
0

What is the most pythonic way depends on what you want when you say "timestamp". A number or a string?

For strings, d.isoformat() is the easiest one. For numbers you do you:

time.mktime(d.timetuple()) + d.microsecond/1000000.0

This is assuming datetime objects. I'm not sure what you mean when you say you want a millisecond accuracy timestamp from date objects. date objects doesn't even have seconds, much less milliseconds. :-)

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • Note that unix timestamps are traditionally UTC, and mktime() is timezone-dependant. Use calendar.timegm() (see http://stackoverflow.com/questions/2956886/python-calendar-timegm-vs-time-mktime). – Beni Cherniavsky-Paskin Apr 17 '12 at 13:44