I am trying to execute this code in VS code, w10 with python 3.8.
from datetime import date
date(2022,10,5).strftime("%-d")
and generate: ValueError: Invalid format string
The same code in Colab works perfectly, and the output is 5. How do i solve this problem?
The -d
directive is not guaranteed to be valid in standard Python, see here for details. Note specifically the bottom of that section (my emphasis):
The full set of format codes supported varies across platforms, because Python calls the platform C library’s
strftime()
function, and platform variations are common. To see the full set of format codes supported on your platform, consult thestrftime(3)
documentation. There are also differences between platforms in handling of unsupported format specifiers.
If the Python you have does not support that format, you can just use this, which will remove any leading zeros from something that is guaranteed to work:
dt = datetime.date(2022, 10, 5)
print(dt.strftime("%d").lstrip("0"))
In fact, I would be doing that regardless of whether %-d
worked or not, just so that my code is more portable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With