The Python Oracle

Format a datetime into a string with milliseconds

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Question
00:19 Accepted answer (Score 583)
00:44 Answer 2 (Score 145)
01:01 Answer 3 (Score 34)
01:51 Answer 4 (Score 29)
02:05 Thank you

--

Full question
https://stackoverflow.com/questions/7588...

Question links:
[datetime]: https://docs.python.org/3/library/dateti...

Answer 1 links:
[isoformat]: https://docs.python.org/3/library/dateti...

Answer 2 links:
[@Cabbi raised the issue]: https://stackoverflow.com/questions/7588...
[Python 2.7]: https://docs.python.org/2/library/dateti...
[documentation]: https://docs.python.org/3/library/dateti...

Answer 3 links:
[strftime]: http://docs.python.org/library/datetime....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime #stringformatting #milliseconds

#avk47



ACCEPTED ANSWER

Score 666


To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

Or shorter:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]
'2022-09-24 10:18:32.926'

See the Python docs for more "%" format codes and the strftime(3) man page for the full list.




ANSWER 2

Score 35


@Cabbi raised the issue that on some systems (Windows with Python 2.7), the microseconds format %f may incorrectly give "0", so it's not portable to simply trim the last three characters. Such systems do not follow the behavior specified by the documentation:

Directive Meaning Example
%f Microsecond as a decimal number, zero-padded to 6 digits. 000000, 000001, …, 999999

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('.')
>>> "%s.%03d" % (dt, int(micro) / 1000)
'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('.')
>>> "%s%03d" % (dt, int(micro) / 1000)
'20160226043839901'



ANSWER 3

Score 31


Using strftime:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
'20220402055654344968'



ANSWER 4

Score 11


Use [:-3] to remove the 3 last characters since %f is for microseconds:

>>> from datetime import datetime
>>> datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]
'2013/12/04 16:50:03.141'