The Python dateutil
library is designed for this [and more]. It will automatically convert this to a datetime
object for you and raise a ValueError
if it can't.
As an example:
>>> from dateutil.parser import parse
>>> parse["2003-09-25"]
datetime.datetime[2003, 9, 25, 0, 0]
This raises a ValueError
if the date is not formatted correctly:
>>> parse["2003-09-251"]
Traceback [most recent call last]:
File "", line 1, in
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
return DEFAULTPARSER.parse[timestr, **kwargs]
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
ret = default.replace[**repl]
ValueError: day is out of range for month
dateutil
is also extremely useful if you start needing to parse other formats in the future, as it can handle most known
formats intelligently and allows you to modify your specification: dateutil
parsing examples.
It also handles timezones if you need that.
Update based on comments: parse
also accepts the keyword argument dayfirst
which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.
>>> parse['11/12/2001']
>>> datetime.datetime[2001, 11, 12, 0, 0] # Nov 12
>>> parse['11/12/2001', dayfirst=True]
>>> datetime.datetime[2001, 12, 11, 0, 0] # Dec 11
I want to check if a string in a dataframe is in datetime format. So far i have tried the following code but it does not give the result i require
Nội dung chính
- Method #1 : Using strptime[]
- Method #2 : Using dateutil.parser.parse[]
- How does Python verify date format?
- How do you validate a date field in Python?
- How do you check if a value is in a date in Python?
- What does date [] do in Python?
import dateutil
from dateutil import parser
dt = dateutil.parser.parse['04-13-1994']
print[dt]
output: 1994-04-13 00:00:00
I expect the result as,
x='04-13-1994'
is_date[x]
output: True
asked Mar 25, 2019 at 17:58
1
Use strptime
import datetime
date_string = '04-23-2019'
try:
date = datetime.datetime.strptime[date_string, '%m-%d-%Y']
except ValueError as err:
print[err]
else:
print[date.year]
print[date.month]
print[date.month]
answered Mar 25, 2019 at 18:07
fiacrefiacre
1,0902 gold badges9 silver badges26 bronze badges
if you need to really check if it matches, use the following code
import re
r = re.compile['\d{1,2}/\d{2}/\d{4}']
if r.match['x/x/xxxx'] is not None:
print 'matches'
else, you can just use a try catch
import dateutil
from dateutil import parser
try:
dt = dateutil.parser.parse['04-13-1994']
print[dt]
except:
print['doesn´t matches']
fiacre
1,0902 gold badges9 silver badges26 bronze badges
answered Mar 25, 2019 at 18:03
4
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format.
Examples:
Input : test_str = ’04-01-1997′, format = “%d-%m-%Y”
Output : True
Explanation : Formats match with date.
Input : test_str = ’04-14-1997′, format = “%d-%m-%Y”
Output : False
Explanation : Month cannot be 14.
Method #1 : Using strptime[]
In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity.
Python3
from
datetime
import
datetime
test_str
=
'04-01-1997'
print
[
"The original string is : "
+
str
[test_str]]
format
=
"%d-%m-%Y"
res
=
True
try
:
res
=
bool
[datetime.strptime[test_str,
format
]]
except
ValueError:
res
=
False
print
[
"Does date match format? : "
+
str
[res]]
Output:
The original string is : 04-01-1997 Does date match format? : True
Method #2 : Using dateutil.parser.parse[]
In this, we check for validated format using different inbuilt function, dateutil.parser. This doesn’t need the format to detect for a date.
Python3
from
dateutil
import
parser
test_str
=
'04-01-1997'
print
[
"The original string is : "
+
str
[test_str]]
format
=
"%d-%m-%Y"
res
=
True
try
:
res
=
bool
[parser.parse[test_str]]
except
ValueError:
res
=
False
print
[
"Does date match format? : "
+
str
[res]]
Output:
The original string is : 04-01-1997 Does date match format? : True
How does Python verify date format?
Method #1 : Using strptime[] In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn't match the format or date, raises the ValueError, and hence can be used to compute for validity.
How do you validate a date field in Python?
Python Program : split['/'] isValidDate = True try: datetime. datetime[int[year], int[month], int[day]] except ValueError: isValidDate = False if[isValidDate]: print["Input date is valid .."] else: print["Input date is not valid.."]
How do you check if a value is in a date in Python?
Use the isinstance built-in function to check if a variable is a datetime object in Python, e.g. if isinstance[today, datetime]: . The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.
What does date [] do in Python?
The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.