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?