简体   繁体   English

Python检查日期格式无法正常工作

[英]Python Checking Date Format Failing to Work

My program takes in data in the form of: 我的程序以以下形式接收数据:

LASTNAME|FIRSTNAME|GENDER|DOB

The first thing I do is use regular expressions to detect the delimiter and split the fields. 我要做的第一件事是使用正则表达式检测分隔符并拆分字段。 I allow a space, comma, or pipe as a delimiter. 我允许使用空格,逗号或管道作为分隔符。 I know which field is DOB and have printed it out to ensure I'm not dealing with the wrong field. 我知道哪个字段是DOB,并已打印出来以确保我没有处理错误的字段。

My try code is as follows: 我的尝试代码如下:

try:
    #check if the fields are good
    fields = re.split(r'[ ,|]+', line)
except:
    #if not good: put it on the failure list
    flist.append(line.replace('\n', ''))

LastName  = fields[0]
FirstName = fields[1]
Gender    = fields[2]
DOB       = fields[3]

#one last try... make sure the DOB is good
try:
    datetime.datetime.strptime(DOB, '%m/%d/%Y')
except:
    flist.append(line.replace('\n', ''))
    raise ValueError("DATE NOT IN RIGHT FORMAT")

I have fed the program multiple lines, and the one in particular I'm feeding: 我已经给程序喂了多行,特别是我正在喂的那一行:

NAME|FAKE|M|09/20/1987

ValueError: time data '09/20/1987' does not match format '%d/%m/%Y'

I've printed out the fields and I've tried converting "DOB" to a string. 我已打印出字段,并尝试将“ DOB”转换为字符串。 I've tried appending the .date() to the end as well. 我也尝试将.date()追加到末尾。 I'm really not sure why it would be failing. 我真的不确定为什么会失败。

@jonrsharpe is right. @jonrsharpe是正确的。 You're trying to parse a MM/DD/YYYY string as DD/MM/YYYY. 您正在尝试将MM / DD / YYYY字符串解析为DD / MM / YYYY。 If all of your dates are in the same format, you should be using '%d/%m/%Y' as your format string. 如果所有日期的格式都相同,则应使用'%d/%m/%Y'作为格式字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM