Get current time in milliseconds since epoch in Python
This post will discuss how to get the current time in milliseconds since the Epoch in Python.
1. Using time.time() function
The standard solution to get the current time since the Epoch is using the time.time() function. It returns time in seconds, which can be easily converted into milliseconds, as shown below:
|
1 2 3 4 5 6 7 |
import time if __name__ == '__main__': millisec = time.time() * 1000 print(millisec) |
It returns a floating-point value that can be easily converted to an integer with the int() function.
|
1 2 3 4 5 6 7 |
import time if __name__ == '__main__': millisec = int(time.time() * 1000) print(millisec) |
2. Using time.time_ns() function
Starting from Python 3.7, you can use the time.time_ns() function, which is similar to time.time() but returns the total number of nanoseconds since the epoch as an integer.
|
1 2 3 4 5 6 7 |
import time if __name__ == '__main__': millisec = time.time_ns() // 1000000 print(millisec) |
3. Using datetime
Another plausible way is to find the current UTC difference with the Epoch time, i.e., 00:00:00 UTC on 1 January 1970, which returns a timedelta object. To get time in seconds, you can use the timedelta.total_seconds() function.
|
1 2 3 4 5 6 7 |
from datetime import datetime if __name__ == '__main__': millisec = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds() * 1000) print(millisec) |
That’s all about getting current time in milliseconds since the epoch in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)