Warm tip: This article is reproduced from serverfault.com, please click

Format a datetime into a string with milliseconds

发布于 2011-09-28 19:28:56

I want to have a datetime string from the date with milliseconds. This code is typical for me and I'm eager to learn how to shorten it.

from datetime import datetime

timeformatted= str(datetime.utcnow())
semiformatted= timeformatted.replace("-","")
almostformatted= semiformatted.replace(":","")
formatted=almostformatted.replace(".","")
withspacegoaway=formatted.replace(" ","")
formattedstripped=withspacegoaway.strip()
print formattedstripped
Questioner
Jurudocs
Viewed
0
Jeremy Moritz 2020-01-29 00:05:55

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])