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
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])
Note, if you want to use
import datetime
instead offrom datetime import datetime
, you'll have to use this:datetime.datetime.utcnow().strftime("%H:%M:%S.%f")
In case microseconds are 0, in windows 2.7 implementation microseconds are not printed out so it trims seconds :(
@cabbi, you could use this instead:
(dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.') ; dt = "%s.%03d" % (dt, int(micro) / 1000) ; print dt
. I added this as an answer.note that this truncates, not rounds to milliseconds
As gens mentions, won't this get it wrong it the first drops number is >=5?. In fact if the usec part is > 999500, then you will never get the time right by fiddling with microseconds part