Converting date to milliseconds since 1-1-70

gry at gry at
Tue Jan 24 21:33:58 CET 2006

NateM wrote:
> How do I convert any given date into a milliseconds value that
> represents the number of milliseconds that have passed since January 1,
> 1970 00:00:00.000 GMT?
> Is there an easy way to do this like Date in java?
> Thanks,
> Nate

The main module for dates and times is "datetime"; so

>>> import datetime
>>> print t
2006-01-24 15:13:35.012755

To get at the "epoch" value, i.e. seconds since 1/1/1970, use the
"time" module:

>>> import time
>>> print time.mktime(t.timetuple())

Now just add in the microseconds:
>>> epoch=time.mktime(d.timetuple())+(t.microsecond/1000000.)
>>> print epoch

Use the "%" formatting operator to display more resolution:
>>> print '%f' % t

Note that the floating point division above is not exact and could
mangle the last digits.

Another way to this data is the datetime.strftime member:

>>> print d.strftime('%s.%%06d') % d.microsecond

This gets you a string, not a number object.  Converting the string to
a number again risks inaccuracy in the last digits:
>>> print float( '1138133615.012755')

More information about the Python-list mailing list