I receive a date value on a POST
request, and it has this format 20220509T000000Z
.
In the system where I am working on, sometimes users can send wrong date values like 2022059T000000Z
and 2022509T000000Z
. That date is saved as string on our database, but if it is incorrect we get issues later doing some calculations and displaying information.
So, I am looking for a way in Python to validate the string is a correct date format, something like this:
#parameter date is the string I receive on the POST
def validate(date):
if date is valid:
# a valid date would be 20220509T000000Z
return true
else:
# an incorrect date would be 2022509T000000Z
return 'Error, incorrect date values'
Thanks in advance
CodePudding user response:
One way is to use dateutil parser in a try and except:
import dateutil
#parameter date is the string I receive on the POST
def validate(date):
try:
dateutil.parser.parse(date)
# a valid date would be 20220509T000000Z
return True
except Exception as e:
# an incorrect date would be 2022509T000000Z
return 'Error, incorrect date values'