python – Format a datetime into a string with milliseconds

python – Format a datetime into a string with milliseconds

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime(%Y-%m-%d %H:%M:%S.%f)[:-3]

>>>> OUTPUT >>>>
2020-05-04 10:18:32.926

Note: For Python3, print requires parentheses:

print(datetime.utcnow().strftime(%Y-%m-%d %H:%M:%S.%f)[:-3])

With Python 3.6 you can use:

from datetime import datetime
datetime.utcnow().isoformat(sep= , timespec=milliseconds)

Output:

2019-05-10 09:08:53.155

More info here: https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat

python – Format a datetime into a string with milliseconds

print datetime.utcnow().strftime(%Y%m%d%H%M%S%f)

http://docs.python.org/library/datetime.html#strftime-strptime-behavior

Leave a Reply

Your email address will not be published. Required fields are marked *