@Cabbi raised the issue that on some systems, the microseconds format %f
may give "0"
, so it's not portable to simply chop off the last three characters.
The following code carefully formats a timestamp with milliseconds:
from datetime import datetime
(dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
dt = "%s.%03d" % (dt, int(micro) / 1000)
print dt
Example Output:
2016-02-26 04:37:53.133
To get the exact output that the OP wanted, we have to strip punctuation characters:
from datetime import datetime
(dt, micro) = datetime.utcnow().strftime('%Y%m%d%H%M%S.%f').split('.')
dt = "%s%03d" % (dt, int(micro) / 1000)
print dt
Example Output:
20160226043839901