Skip to content
Advertisement

Format a datetime into a string with milliseconds

How can I format a datetime object as a string with milliseconds?

Advertisement

Answer

To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

Or slightly shorter:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement