【发布时间】:2021-08-14 04:41:03
【问题描述】:
我目前正在编写一个对日期进行排序的脚本。我有一个名为sample.txt 的输入文件和一个名为sample2.txt 的输出文件。最后,输入文件的内容应该被排序并写入输出文件。但是在运行我的脚本时,我遇到了以下错误:Unconverted Data Remains: Dentist。这是因为strptime 无法转换Dentist。所以我的问题是:如何在不删除 Dentist 一词或其他无日期内容的情况下修复此错误?
这是完整的错误信息:
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))
提前感谢您的每一个帮助和建议:)
【问题讨论】:
标签: python python-3.x sorting datetime strptime