How do I check if a string can be parsed to a date?
- Jan 19, 1990
- January 19, 1990
- Jan 19,1990
- 01/19/1990
- 01/19/90
- 1990
- Jan 1990
- January1990
These are all valid dates. If there's any concern regarding the lack of space in between stuff in item #3 and the last item above, that can be easily remedied via automatically inserting a space in between letters/characters and numbers, if so needed.
But first, the basics:
I tried putting it in an if statement
:
if datetime.strptime(item, '%Y') or datetime.strptime(item, '%b %d %y') or datetime.strptime(item, '%b %d %Y') or datetime.strptime(item, '%B %d %y') or datetime.strptime(item, '%B %d %Y'):
But that's in a try-except block, and keeps returning something like this:
16343 time data 'JUNE1890' does not match format '%Y'
Unless, it met the first condition in the if
statement.
To clarify, I don't actually need the value of the date – I just want to know if it is. Ideally, it would've been something like this:
if item is date:
print date
else:
print "Not a date"
Is there any way to do this?
Best Solution
The
parse
function indateutils.parser
is capable of parsing many date string formats to adatetime
object.If you simply want to know whether a particular string could represent or contain a valid date, you could try the following simple function:
Then you have:
Custom parsing
parse
might recognise some strings as dates which you don't want to treat as dates. For example:Parsing
"12"
and"1999"
will return a datetime object representing the current date with the day and year substituted for the number in the string"23, 4"
and"23 4"
will be parsed asdatetime.datetime(2023, 4, 16, 0, 0)
."Friday"
will return the date of the nearest Friday in the future."August"
corresponds to the current date with the month changed to August.Also
parse
is not locale aware, so does not recognise months or days of the week in languages other than English.Both of these issues can be addressed to some extent by using a custom
parserinfo
class, which defines how month and day names are recognised:An instance of this class can then be used with
parse
: