Python strftime milliseconds 3 digits

Python strftime Milliseconds (3 digits)

In Python, the strftime() method is used to convert date and time objects to string representation, based on a given format. To display milliseconds with 3 digits using strftime(), you can use the %f directive.

Here’s an example:


import datetime

now = datetime.datetime.now()
milliseconds = now.strftime("%f")[:3]

print(milliseconds)

In the example above, we import the datetime module and get the current datetime using the now() function. Then, we use the strftime() method with the format string "%f" to get the milliseconds as a string with up to 6 digits. To obtain only the first 3 digits of the milliseconds, we use slicing with [:3]. Finally, we print the result.

Output:


314

The output will vary depending on the current time you run the code.

Leave a comment