3

I have a program where the user selects a date from a datepicker, and I need to convert this date to another format.

The original format is %d/%m/%Y and I need to convert it to %-d-%b-%Y.

I made a small example of what happens:

from datetime import datetime
# Import tkinter library
from tkinter import *
from tkcalendar import Calendar, DateEntry

win = Tk()
win.geometry("750x250")
win.title("Example")


def convert():
    date1 = cal.get()
    datetimeobject = datetime.strptime(date1, '%d/%m/%Y')
    print(date1)
    new_format = datetimeobject.strftime('%-d-%b-%Y')
    print(new_format)


cal = DateEntry(win, width=16, background="gray61", foreground="white", bd=2, date_pattern='dd/mm/y')
cal.pack(pady=20)

btn = Button(win, command=convert, text='PRESS')
btn.pack(pady=50)

win.mainloop()

This gives me the following error:

  File "---------\date.py", line 15, in convert
    new_format = datetimeobject.strftime('%-d-%b-%Y')
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: Invalid format string
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

2 Answers2

3

The error is due to the use of the %-d format specifier in the strftime() method. This specifier is not supported in the Windows platform.

To resolve this issue, you can replace the %-d format specifier with %d and remove the -.

Manualmsdos
  • 1,505
  • 3
  • 11
  • 22
Qbasix
  • 55
  • 7
  • Oh indeed, you're right: https://stackoverflow.com/questions/28894172/why-does-d-or-e-remove-the-leading-space-or-zero – Swifty May 05 '23 at 13:26
  • 1
    Hi, Qbasix! Several of your recent answers appear likely to be entirely or partially written by AI (e.g., ChatGPT). Please be aware that [posting AI-generated content is not allowed here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with any answer, I would encourage you to delete it. Thanks! – NotTheDr01ds Jul 18 '23 at 11:37
  • 1
    **Readers should review this answer carefully and critically, as AI-generated information often contains fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. – NotTheDr01ds Jul 18 '23 at 11:37
2

The reason why that gives an error is because %-d only works on Unix machines (Linux, MacOS). On Windows (or Cygwin), you have to use %#d.

Programmer-RZ
  • 166
  • 1
  • 9