In Python, you can use datetime
the module and strftime()
function to format the current time. Here's an example that prints out the current time to milliseconds as a time string:
import datetime
now = datetime.datetime.now()
milliseconds = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
print(milliseconds)
In this example, first use datetime.datetime.now()
the function to get the current time. Then, use strftime()
the function to format the time as a string. %f
It is used to represent milliseconds, since %f
will output six digits to represent milliseconds, we need to use [:-3]
to intercept the previous 23 digits.
This code will print out a string of the current time in the format "2022-09-30 12:23:45.678", where the last three digits represent milliseconds.