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?
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 .
Bookmark this question. Show activity on this post. I have a list of unix timestamps that all contain milliseconds -- they are 13 digits long.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With