Python datetime format string excluding zeros

Question:

str(datetime.date.today())

I get: 2023-04-01

I need: 2023-4-1

If I format it to remove zeros then I will face an issue if the date is 2023-10-20

How can I do it quick and simple. I need it as a string.

Asked By: CODComputerAtWar

||

Answers:

You can always format yourself, since the datetime module doesn’t appear to have a portable way to do it:

>>> import datetime as dt
>>> d=dt.date.today()
>>> f'{d.year}-{d.month}-{d.day}'
'2023-4-1'
Answered By: Mark Tolonen
import datetime

today = datetime.date.today()
formatted_date = today.strftime("%Y-%-m-%-d")
print(formatted_date)
Answered By: len
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.