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?
Have a look at the
parse
function indateutils.parser
. It's capable of parsing almost any string to adatetime
object.If you simply want to know whether a particular string could represent a date, you could try the following function:
Then you have:
One note of caution:
parse
might recognise some strings as dates which you don't want to treat as dates, e.g."23, 4"
will be parsed asdatetime.datetime(2023, 4, 16, 0, 0)
. You might need additional checks if you want to catch these cases.If you want to parse those particular formats, you can just match against a list of formats:
Prints: