In this tutorial, we are going to discuss how we can represent and manipulate milliseconds in Python. In a modern, fast-paced computing environment, precise tracking of time, including milliseconds, is essential for scheduling tasks, debugging, or simply reporting the time it takes for code to execute.
Step 1: Using the Time Module
The first and most straightforward method you’ll learn is to use the built-in time module in Python. We can use time.time(), which returns the time in seconds since the epoch as a floating point number. We are interested in milliseconds, so we will multiply the return value by 1000.
Here is an example:
1 2 3 4 |
import time current_milli_time = lambda: int(round(time.time() * 1000)) print(current_milli_time()) |
Step 2: Using the Datetime Module
Another way of fetching the current time in milliseconds is by using Python’s built-in datetime module.
The datetime module has a microsecond component in its time. Given that 1 millisecond equals 1000 microseconds, you need to divide by 1000 to get milliseconds.
Here is the Python code for the same:
1 2 3 4 |
from datetime import datetime current_milli_time = lambda: int(round(datetime.now().timestamp() * 1000)) print(current_milli_time()) |
Step 3: Using Raw Time in Milliseconds
It is also fairly common in Python to return the raw time in milliseconds. This may be useful if your application requires this particular format.
1 2 3 4 |
import time milliseconds = int(round(time.time() * 1000)) print(milliseconds) |
Full Code:
Displaying the final version of the code with both methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import time from datetime import datetime # Using time module current_milli_time = lambda: int(round(time.time() * 1000)) print(current_milli_time()) # Using datetime module current_milli_time = lambda: int(round(datetime.now().timestamp() * 1000)) print(current_milli_time()) # Display raw time in milliseconds milliseconds = int(round(time.time() * 1000)) print(milliseconds) |
1690542661380 1690542661380 1690542661380
Conclusion
In Python, the time and datetime modules make it easy to represent and work with time data, including milliseconds. Whether you’re timing code execution or tracking real-world time, this flexible and easy-to-use functionality is a powerful tool for your development toolkit.