问题描述:

I'm unpacking some data from a file, and some of the birthdates has different formats. I need to check if the dates has the right format, and then change them to the right format.

So, here is my code:

 name, birthdate, residence, gender = line.split('|')

try:

birthdate == datetime.strptime(birthdate, '%y/%m/%d')

except ValueError:

print("Wrong format!")

birthdates_list.append(birthdate)

And then:

for birthdates in birthdates_list:

if birthdates == datetime.strptime(birthdates, '%y/%m/%d'):

pass

else:

print("Wrong format!")

But i get the error:

Wrong format!

File ".\dates.py", line 47, in <module>

if birthdates = datetime.strptime(birthdates, '%y/%m/%d'):

File "C:\Python34\lib\_strptime.py", line 500, in _strptime_datetime

tt, fraction = _strptime(data_string, format)

File "C:\Python34\lib\_strptime.py", line 337, in _strptime

(data_string, format))

ValueError: time data '1978/05/17' does not match format '%y/%m/%d'

1978/05/17 is the exact same format as %y/%m/%d, so why does it say that?

网友答案:

"1978/05/17 is the exact same format as %y/%m/%d" - nope, %y would match '78', not '1978'; see docs.python.org/3/library/…. – jonrsharpe

Thanks!

It worked! Onto the next thing, what would be the best way to force the other dates (which is not in that format, suddenly %d/%m/%Y) to the format %Y/%m/%d?

相关阅读:
Top