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]