zarrin
zarrin

Reputation: 61

check if a string is in datetime (mm-dd-yyyy) format in a data frame in python

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

Answers (2)

Mateus Martins
Mateus Martins

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

fiacre
fiacre

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

Related Questions