Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python strftime("%-d") generate Invalid format string [duplicate]

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?

like image 374
juliancaba Avatar asked Sep 15 '25 08:09

juliancaba


1 Answers

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 the strftime(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.

like image 75
paxdiablo Avatar answered Sep 17 '25 22:09

paxdiablo