0

I am using this code to format dates:

from datetime import datetime

pictureData = datetime.strptime('2022-01-03', '%Y-%m-%d')
pictureData = pictureData.strftime("%Y-%-m-%-d")
print(pictureData)

This works great on Mac, printing 2022-1-3; but gives this error on Windows:

Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\file.py", line 17, in <module>
pictureData = pictureData.strftime("%Y-%-m-%-d")
ValueError: Invalid format string

I want to remove the padding zero before the 01 and 03. How can I make this work in a cross-platform way?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
James Bond
  • 41
  • 5
  • what's the error message? – eshirvana Jan 02 '22 at 21:52
  • pictureData = pictureData.strftime("%Y-%-m-%-d") ValueError: Invalid format string They this is the error I'm getting @eshirvana – James Bond Jan 02 '22 at 21:53
  • Please read https://meta.stackoverflow.com/questions/359146 and show a *complete* error message - copied and pasted, starting from the line that says `Traceback (most recent call last):`, and formatted as code. – Karl Knechtel Jan 02 '22 at 21:53
  • The short version is that `strftime` relies on an underlying system call, and the Windows version of it doesn't support all the extensions that the Linux version does. You can only rely on the features [described in the documentation](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes). You can work around this by using ordinary string formatting and interpolating field values from the `datetime` object, as shown in one of the answers on the linked duplicate. – Karl Knechtel Jan 02 '22 at 21:58
  • @eshirvana Error messages are typically designed with the expectation that they will be presented and read in a terminal window, i.e. with a monospace font. It is generally a better idea, therefore, to format them as code rather than as a block quote. – Karl Knechtel Jan 02 '22 at 22:00
  • @KarlKnechtel Thank you for your help. I understood what you said. it really helped. for windows you use # instead of -. – James Bond Jan 02 '22 at 22:05

0 Answers0