Search code examples
pythondatetimestring-formattingmilliseconds

Format a datetime into a string with milliseconds


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


Solution

  • 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 shorter:

    >>> from datetime import datetime
    >>> datetime.utcnow().strftime('%F %T.%f')[:-3]
    '2022-09-24 10:18:32.926'
    

    See the Python docs for more "%" format codes and the strftime(3) man page for the full list.