datetime to Unix timestamp with millisecond precision

Datetime objects have a field named microsecond. So one way to achieve what you need is:

time.mktime(then.timetuple())*1e3 + then.microsecond/1e3

This returns milliseconds since UNIX epoch with the required precision.


Assuming someone is interested in UTC, the following in valid after Python 3.3:

from datetime import datetime

now = int(datetime.utcnow().timestamp()*1e3)

Python 3.3 release notes:

New datetime.datetime.timestamp() method: Return POSIX timestamp corresponding to the datetime instance.

Intermediate results:

In [1]: datetime.utcnow().timestamp()
Out[1]: 1582562542.407362

In [2]: datetime.utcnow().timestamp()*1e3
Out[2]: 1582562566701.329

In [3]: int(datetime.utcnow().timestamp()*1e3)
Out[3]: 1582562577296

In Python 3.3 and above, which support the datetime.timestamp() method, you can do this:

from datetime import datetime, timezone, timedelta

(datetime.now(timezone.utc) + timedelta(days=3)).timestamp() * 1e3