Format a datetime into a string with milliseconds


Question

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
1
125
9/28/2011 7:34:13 PM

Accepted Answer

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 >>>>
2018-10-04 10:18:32.926
277
6/1/2018 2:23:34 PM

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon