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.
Use the getTime() method to convert a date to a timestamp, e.g. new Date(). getTime() . The getTime method returns the number of milliseconds elapsed between the 1st of January, 1970 and the given date.
You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.
Method 2: Using datetime. In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function. Returns : It returns the string representation of the date or time object.
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
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