How do I validate a date string format in python?
>>> import datetime
>>> def validate(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
>>> validate('2003-12-23')
>>> validate('2003-12-32')
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
validate('2003-12-32')
File "<pyshell#18>", line 5, in validate
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
ValueError: Incorrect data format, should be YYYY-MM-DD
Check if string has date, any format
The parse
function in dateutils.parser
is capable of parsing many date string formats to a datetime
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:
from dateutil.parser import parse
def is_date(string, fuzzy=False):
"""
Return whether the string can be interpreted as a date.
:param string: str, string to check for date
:param fuzzy: bool, ignore unknown tokens in string if True
"""
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False
Then you have:
>>> is_date("1990-12-1")
True
>>> is_date("2005/3")
True
>>> is_date("Jan 19, 1990")
True
>>> is_date("today is 2019-03-27")
False
>>> is_date("today is 2019-03-27", fuzzy=True)
True
>>> is_date("Monday at 12:01am")
True
>>> is_date("xyz_not_a_date")
False
>>> is_date("yesterday")
False
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.- Similarly
"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:
from dateutil.parser import parserinfo
class CustomParserInfo(parserinfo):
# three months in Spanish for illustration
MONTHS = [("Enero", "Enero"), ("Feb", "Febrero"), ("Marzo", "Marzo")]
An instance of this class can then be used with parse
:
>>> parse("Enero 1990")
# ValueError: Unknown string format
>>> parse("Enero 1990", parserinfo=CustomParserInfo())
datetime.datetime(1990, 1, 27, 0, 0)
how to validate a date in python
Rather than use time.strptime()
, use datetime.datetime.strptime()
and then validate the resulting object to be within your range:
from datetime import datetime, date
date_input = input('Date (mm/dd/yyyy): ')
try:
valid_date = datetime.strptime(date_input, '%m/%d/%Y').date()
if not (date(2014, 1, 1) <= valid_date <= date(2014, 8, 7)):
raise ValueError('Date out of range')
except ValueError:
print('Invalid date!')
If no exception is thrown, valid_date
is bound to a datetime.date()
instance.
How to validate a string input in python using datetime library and keep prompting user for input until valid input?
This code works on my machine, and it prompts the user to input again if it doesn't succeed.
import datetime
format = "%Y-%m-%d"
while(True):
date_string = input("> ").strip()
try:
datetime.datetime.strptime(date_string, format)
print("This is the correct date string format.")
break
except ValueError:
print("This is the incorrect date string format. It should be YYYY-MM-DD")
validate date format in python [with regex or any built in method]
you can use datetime for this (in python 2.7)
from datetime import datetime
date_string = '20170808'
if len(date_string) == 8:
datetime.strptime(date_string, '%Y%m%d')
else:
raise ValueError('date need to be in format YYYYMMDD ')
if you date is not valid than you get:
a ValueError Exception
ValueError: unconverted data remains: 0
Checking if date is valid with two different format
Simply do try for each datetime.strptime and catch each error seperatly.
def dateValidate(date):
try:
datetime.strptime(date, "%Y-%m-%d")
return 1
except ValueError:
try:
datetime.strptime(date, "%m/%d/%Y")
return 2
except ValueError:
return -1
Related Topics
Python VS Groovy VS Ruby? (Based on Criteria Listed in Question)
How to Integrate a Standalone Python Script into a Rails Application
Integration Testing for a Web App
How to Write a Perl, Python, or Ruby Program to Change the Memory of Another Process on Windows
Convert Backward Slash to Forward Slash in Python
What's the Ruby Equivalent of Python's Os.Walk
Restrictons of Python Compared to Ruby: Lambda'S
Efficient Ways to Duplicate Array/List in Python
Python Equivalent of Ruby's Each_Slice(Count)
Equivalent to Python's Findall() Method in Ruby
Ruby Hash Equivalent to Python Dict Setdefault
Does Ruby Support Conditional Regular Expressions
Urllib2 in Python Equivalent for Ruby
Why Is Ruby More Suitable for Rails Than Python
The Simplest Possible Reverse Proxy