时间数据与格式不匹配(应该是)

时间:2015-11-04 15:09:06

标签: datetime python-3.x strptime

我正在从文件中解压缩一些数据,并且一些生日具有不同的格式。我需要检查日期是否格式正确,然后将其更改为正确的格式。

所以,这是我的代码:

   name, birthdate, residence, gender = line.split('|')
   try:
    birthdate == datetime.strptime(birthdate, '%y/%m/%d')
   except ValueError:
    print("Wrong format!")

   birthdates_list.append(birthdate)

然后:

for birthdates in birthdates_list:
  if birthdates == datetime.strptime(birthdates, '%y/%m/%d'):
    pass
  else:
    print("Wrong format!")

但我得到错误:

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与%y /%m /%d的格式完全相同,为什么会这样说呢?

1 个答案:

答案 0 :(得分:0)

“1978/05/17与%y /%m /%d的格式完全相同” - 不,%y匹配'78',而不是'1978';请参阅docs.python.org/3/library/... - jonrsharpe

谢谢!

有效!接下来,强制其他日期(不是那种格式,突然%d /%m /%Y)的最佳方法是格式%Y /%m /%d?