0
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.

  • 1
    What is wrong with `2023-10-20`? – roganjosh Apr 01 '23 at 18:25
  • nothing wrong with 2023-10-20 (Its just an example I mentioned), The question is regarding converting 2023-04-01 to 2023-4-1 – CODComputerAtWar Apr 01 '23 at 18:27
  • 1
    Your question literally states "then I will face an issue if the date is 2023-10-20". Have you even looked at the `datetime` module in python for formatting? – roganjosh Apr 01 '23 at 18:28
  • between I have checked datetime model I didn't see anything regarding what I need. – CODComputerAtWar Apr 01 '23 at 18:32
  • I'm going to ignore all of that (millions of people move between countries) but there is no directive to get the format you want in the base [datetime module](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes) it seems. I'm not sure why you need this format in the first place – roganjosh Apr 01 '23 at 18:33
  • Another duplicate: [Python datetime formatting without zero-padding](https://stackoverflow.com/questions/9525944/python-datetime-formatting-without-zero-padding) – LercDsgn Apr 01 '23 at 18:34
  • @roganjosh I am building a boat that runs using code instead of fuel, and the best part the speakers sing dolphins and whales. Thnx – CODComputerAtWar Apr 01 '23 at 18:43
  • @LercDsgn Tack så mycket – CODComputerAtWar Apr 01 '23 at 18:46

2 Answers2

1

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'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1
import datetime

today = datetime.date.today()
formatted_date = today.strftime("%Y-%-m-%-d")
print(formatted_date)
len
  • 749
  • 1
  • 8
  • 23