时间数据与格式不匹配(应该是)
Time data does not match format (should be)
我正在从文件中解压一些数据,其中一些生日的格式不同。我需要检查日期的格式是否正确,然后将它们更改为正确的格式。
所以,这是我的代码:
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 格式完全相同,为什么这么说?
“1978/05/17 与 %y/%m/%d 的格式完全相同”- 不,%y 将匹配“78”,而不是“1978”;参见 docs.python.org/3/library/…。 – 乔恩夏普
谢谢!
成功了!接下来,将其他日期(不是那种格式,突然 %d/%m/%Y)强制为格式 %Y/%m/%d 的最佳方法是什么?
我正在从文件中解压一些数据,其中一些生日的格式不同。我需要检查日期的格式是否正确,然后将它们更改为正确的格式。
所以,这是我的代码:
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 格式完全相同,为什么这么说?
“1978/05/17 与 %y/%m/%d 的格式完全相同”- 不,%y 将匹配“78”,而不是“1978”;参见 docs.python.org/3/library/…。 – 乔恩夏普
谢谢!
成功了!接下来,将其他日期(不是那种格式,突然 %d/%m/%Y)强制为格式 %Y/%m/%d 的最佳方法是什么?