Home > Software engineering >  ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must b
ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must b

Time:07-05

I'm scraping a website for data to include in my project and while fetching the date it comes in a mm-dd-yyyy format like so "July 9, 2022". Is there a way to bypass this and avoid the error?

for test_job in final_jobs:    
    newjob = Jobs.objects.create(
        title = test_job['title'],
        location = test_job['location'],
        date_posted = test_job['date_posted'],
        closing_date = test_job['closing_date'],
        )

the error:

ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must be in YYYY-MM-DD format.

CodePudding user response:

You can use the strptime function to convert your date to an actual date object, which Django will then happily accept

See these 2 sections of the Python documentation for more:
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

In this instance it seems, that you can just do

date_posted = datetime.strptime(test_job['date_posted'], "\n- %B %d, %Y\n")
closing_date = datetime.strptime(test_job['closing_date'], "\n- %B %d, %Y\n")

however additional processing of the strings may be needed if the format sligthly deviates every time

CodePudding user response:

you can change the settings in the setting see here https://docs.djangoproject.com/fr/4.0/ref/settings/#date-format

  • Related