解决Unconverted Data Remains: Error without replace other file contents

Resolve Unconverted Data Remains: Error without replace other file contents

我目前正在编写一个对日期进行排序的脚本。我有一个名为 sample.txt 的输入文件和一个名为 sample2.txt 的输出文件。最后,输入文件的内容应该被排序并写入输出文件。但是当运行我的脚本我运行进入以下错误:Unconverted Data Remains: Dentist。这是因为strptime无法转换Dentist造成的。所以我的问题是:如何在不删除 Dentist 或其他 none 日期内容的情况下修复此错误?

这是完整的错误信息:

Traceback (most recent call last):
  File "test3.py", line 156, in <module>
    main_user_input.user_input()
  File "test3.py", line 144, in user_input
    list_next_appointments.list_next_appointments_main()
  File "test3.py", line 96, in list_next_appointments_main
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
  File "test3.py", line 96, in <lambda>
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
  File "/home/supre/anaconda3/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/home/supre/anaconda3/lib/python3.8/_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains:  Dentist

这是我的输入文件的内容:

23.08.2021 Dentist 
13.08.2031 Surgery 
13.01.2022 Family 

这是我的代码:

with open('sample.txt', 'r') as file1, open('sample2.txt','w+') as file2:
    bands = (line.strip() for line in file1)
    bands = sorted(bands, key=lambda date: datetime.strptime(date, "%d.%m.%Y"))
    file2.write(' \n'.join(bands))

提前感谢大家的帮助和建议:)

如果您的输入文件总是按照您显示的方式进行格式化,即在 2 列中,避免错误的最简单方法是使用 .strptime 仅转换日期列。换句话说,将行拆分为日期文本并休息:


with open('sample.txt', 'r') as file1, open('sample2.txt','w+') as file2:
    bands = (line.strip() for line in file1)
    bands = sorted(bands, key=lambda line: datetime.strptime(line.split()[0], "%d.%m.%Y"))
    file2.write(' \n'.join(bands))