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.

8
  • 1
    What is wrong with 2023-10-20? Commented Apr 1, 2023 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 Commented Apr 1, 2023 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? Commented Apr 1, 2023 at 18:28
  • between I have checked datetime model I didn't see anything regarding what I need. Commented Apr 1, 2023 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 it seems. I'm not sure why you need this format in the first place Commented Apr 1, 2023 at 18:33

2 Answers 2

1
import datetime

today = datetime.date.today()
formatted_date = today.strftime("%Y-%-m-%-d")
print(formatted_date)
Sign up to request clarification or add additional context in comments.

1 Comment

note %- directives are platform-specific, for instance they don't work on Windows.
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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.