0

I was printing str(datetime.now()) after every few milliseconds and to my surprise, it sometimes skip writing milliseconds. As you can see it didnt write milliseconds for 2021-06-15 14:08:42. I want to make sure it prints milliseconds, even though if its 2021-06-15 14:08:42.000000

2021-06-15 14:08:41.898284
2021-06-15 14:08:41.949136
2021-06-15 14:08:42
2021-06-15 14:08:42.050864
2021-06-15 14:08:42.100730
Muhammad Naufil
  • 2,420
  • 2
  • 17
  • 48
  • I recommend looking at https://stackoverflow.com/a/6539677/5601284, which you can use to print floating point numbers at arbitrary levels of precision. You need to get the float first though. If you want to cheat, you can check the length of the string and append some "0" characters – byxor Jun 15 '21 at 12:27
  • 1
    @byxor datetime objects are not floating point numbers though? – xrisk Jun 15 '21 at 12:30
  • @xrisk correct, I never said they were. That's why I said "you need to get the float first though", because to format a float, you need a float (representing the seconds/milliseconds). Weirdly enough I thought I deleted the comment but I guess my net lagged. – byxor Jun 15 '21 at 14:05

2 Answers2

2

This is according to spec.

Return a string representing the date and time in ISO 8601 format:

YYYY-MM-DDTHH:MM:SS.ffffff, if microsecond is not 0

YYYY-MM-DDTHH:MM:SS, if microsecond is 0

If you want to precisely control the formatting, you should use datetime.strftime.

As MrFuppes mentions, you can also use the datetime.isoformat function but pass timespec=microseconds in order to always show the microseconds.

xrisk
  • 3,790
  • 22
  • 45
  • 1
    datetime objects also have an [isoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat) method; which allows you to set a keyword `timespec` that controls the precision of the output. More convenient than `strftime` I think. – FObersteiner Jun 15 '21 at 12:33
1

Just string-pad the result: str(datetime.now()).ljust(26, '0'). 26 was chosen since that's the "normal" length/precision above (e.g. len('2021-06-15 14:08:41.898284') equals 26).

blacksite
  • 12,086
  • 10
  • 64
  • 109