[英]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
Use strptime使用 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)
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否则,您可以使用 try catch
import dateutil
from dateutil import parser
try:
dt = dateutil.parser.parse('04-13-1994')
print(dt)
except:
print('doesn´t matches')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.