Reputation: 61
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
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
Upvotes: 4
Views: 7321
Reputation: 442
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')
Upvotes: 2
Reputation: 1180
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)
Upvotes: 4