A
A
Alex Xmel2021-07-02 13:41:28
Django
Alex Xmel, 2021-07-02 13:41:28

How to correctly convert a string to a date?

Sobsna the question in the title is how to correctly translate a string containing a date into a datetime object?

I get the string from the site: (if it matters, I use bootstrap 5)
The string arrives to me in this form: '2021-07-05'
I can easily translate it into a date like this: datetime.datetime.strptime('2021-07-05 ', '%Y-%m-%d')

but here's what I thought about:
1. If the string looks like this: '2021 07 05' then I already get an error. That is, a separator other than a dash.
2. Now I know that I have a year, then a month, then a day. What if another user uses a different date format? How can I understand here '2021-07-05' where is the month? probably a certain flag from the page should somehow arrive?

ps I suspect that you need to use js, but I don’t want to fence the garden where it is not needed. Maybe the simplest solution is to give the user three separate lists with month, year and day?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-07-02
@Desead

Desead , firstly, connect this cleave.js library in the template, it will help to form the date in the correct format. Secondly, on the backend you need to use forms with date format validation, if the date is not in the correct format, then do not perform further actions, but show the error to the user. But as a rule, the first condition solves this problem

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question