Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime to Unix timestamp with millisecond precision

I'm trying to do something really simple, convert a datetime object three days into the future into a Unix UTC timestamp:

import datetime, time then = datetime.datetime.now() + datetime.timedelta(days=3) # Method 1 print then.strftime("%s") # Method 2 print time.mktime(then.timetuple()) # Method 3  print time.mktime(then.timetuple()) * 1000 

Method 1 and 2 give me Unix time in seconds, not milliseconds, and method 3 gives me milliseconds with no actual millisecond precision.

When I simply print then, I get datetime.datetime(2011, 11, 19, 15, 16, 8, 278271), so I know that the precision is available for milliseconds. How can I get a Unix timestamp with actual millisecond precision? If it's returned as a float and I have to flatten it to an an int, that's fine. Is there a solution I'm looking for that does this?

like image 292
Naftuli Kay Avatar asked Nov 16 '11 23:11

Naftuli Kay


People also ask

How do you convert DateTime to milliseconds?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

Does Unix timestamp have milliseconds?

Bookmark this question. Show activity on this post. I have a list of unix timestamps that all contain milliseconds -- they are 13 digits long.

How do you epoch milliseconds?

Convert from human-readable date to epoch long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds.


2 Answers

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.

like image 77
Adam Zalcman Avatar answered Nov 07 '22 10:11

Adam Zalcman


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 
like image 30
Rob Smallshire Avatar answered Nov 07 '22 09:11

Rob Smallshire