Python strftime microseconds 3 digits

Python strftime Microseconds 3 Digits

The strftime function in Python is used to format a datetime object into a string representation. It allows you to specify a format string that defines how the resulting string should look like.

By default, the strftime function does not include microseconds in its output. However, you can use the “%f” directive in the format string to display microseconds with 6 digits. To display the microseconds with 3 digits, you need to manipulate the datetime object before calling strftime.

Here’s an example:

from datetime import datetime

# Create a datetime object
dt = datetime.now()

# Truncate microseconds to 3 digits
dt = dt.replace(microsecond=dt.microsecond // 1000 * 1000)

# Format the datetime object
formatted = dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]

# Print the formatted string
print(formatted)

In this example, we first create a datetime object using the datetime.now() function. Then, we truncate the microseconds to 3 digits by dividing the number of microseconds by 1000, rounding down, and multiplying by 1000 again. This effectively removes the last 3 digits from the microseconds.

After truncating the microseconds, we can use the strftime function to format the datetime object according to a desired format string. In this case, we use the format string "%Y-%m-%d %H:%M:%S.%f" to include the year, month, day, hour, minute, second, and microseconds with 6 digits.

Finally, we slice the formatted string to exclude the last 3 digits from the microseconds by using [:-3]. This will give us the desired output with microseconds having 3 digits.

Here’s an example output:

2022-12-31 23:59:59.999

Leave a comment