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)
Check if a string is a date value
Would Date.parse()
suffice?
See its relative MDN Documentation page.
Date.parse
returns a timestamp if string date is valid. Here are some use cases:
// /!\ from now (2021) date interpretation changes a lot depending on the browser
Date.parse('01 Jan 1901 00:00:00 GMT') // -2177452800000
Date.parse('01/01/2012') // 1325372400000
Date.parse('153') // NaN (firefox) -57338928561000 (chrome)
Date.parse('string') // NaN
Date.parse(1) // NaN (firefox) 978303600000 (chrome)
Date.parse(1000) // -30610224000000 from 1000 it seems to be treated as year
Date.parse(1000, 12, 12) // -30610224000000 but days and month are not taken in account like in new Date(year, month,day...)
Date.parse(new Date(1970, 1, 0)) // 2588400000
// update with edge cases from comments
Date.parse('4.3') // NaN (firefox) 986248800000 (chrome)
Date.parse('2013-02-31') // NaN (firefox) 1362268800000 (chrome)
Date.parse("My Name 8") // NaN (firefox) 996616800000 (chrome)
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 input string contains date(specially in the format yy-mm-dd) using python
The dateutil library is your best friend when it comes to parsing dates:
>>> from dateutil.parser import *
>>> parse('2003-12-23')
datetime.datetime(2003, 12, 23, 0, 0)
>>> parse('2003-12-32')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1356, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 653, in parse
ret = self._build_naive(res, default)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1227, in _build_naive
naive = default.replace(**repl)
ValueError: day is out of range for month
>>>
If you want to be more restrictive, ie. only accept dates with the YYYY-MM-DD
format, then checking with a regex first might be your thing:
def is_date(ds):
if re.match(r'\d{4}-\d{2}-\d{2}', ds):
return bool(parse(ds))
return False
>>> is_date('2003-12-23')
True
>>> is_date('2003-12-32')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in is_date
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1356, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 653, in parse
ret = self._build_naive(res, default)
File "c:\srv\venv\dev\lib\site-packages\dateutil\parser\_parser.py", line 1227, in _build_naive
naive = default.replace(**repl)
ValueError: day is out of range for month
If you don't want to be quite as restrictive, but accept all iso-formatted dates, then:
from dateutil.parser import isoparse
>>> isoparse('2003-12-23')
datetime.datetime(2003, 12, 23, 0, 0)
>>> isoparse('20031223')
datetime.datetime(2003, 12, 23, 0, 0)
How to check if a string is date?
Other person are also correct
This is your answer
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class date {
public static boolean isValidDate(String inDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:ms");
dateFormat.setLenient(false);
try {
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(isValidDate("20-01-2014"));
System.out.println(isValidDate("11-04-2015 22:01:33:023"));
System.out.println(isValidDate("32476347656435"));
}
}
Correctly determine if date string is a valid date in that format
You can use DateTime::createFromFormat()
for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavić.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
Demo!
Check if a string is a date or not
Here is a simple function that uses Date.parse() internally; when you pass a string with whitespaces to Date.parse()
, it will ignore non-digit chars and will return positive; hence you need to remove the space characters before passing it to Date.parse()
const a= 'Check 134';const b= '2020-01-15T10:47:54Z';const c= '1234';const tricky = '1'; // a number from -12 to 13 is valid
function isValidDate (str) { // optional condition to eliminate the tricky ones // since chrome will prepend zeros (000...) to the string and then parse it let noSpace = str.replace(/\s/g, '') if( noSpace.length < 3) { return false } return Date.parse(noSpace) > 0}
console.log(a,isValidDate(a))console.log(b,isValidDate(b))console.log(c,isValidDate(c))console.log(tricky,isValidDate(tricky))
// only in chromeconsole.log("'1' is ", Date.parse('1') > 1 ," since it can be ", new Date('1').toString())
Related Topics
Find P-Value (Significance) in Scikit-Learn Linearregression
Imports in _Init_.Py and 'Import As' Statement
Executing Multiple Statements with Postgresql via SQLalchemy Does Not Persist Changes
How to Get a Raw, Compiled SQL Query from a SQLalchemy Expression
Differencebetween Root.Destroy() and Root.Quit()
Subprocess Readline Hangs Waiting for Eof
Merging Two CSV Files Using Python
Python: Download a File from an Ftp Server
How Does _Contains_ Work for Ndarrays
Replacing Text in a File with Python
Executing Command Using Paramiko Exec_Command on Device Is Not Working
Django Return Redirect() with Parameters
Implement Matlab's Im2Col 'Sliding' in Python