看到你的代码,问题出在读取时间字符串时,没有正确处理字符串中的额外字符和空白字符。你可以尝试修改read_time_from_file函数中的代码如下:def read_time_from_file(start_time_file, end_time_file): with open(start_time_file, 'r') as start_file, open(end_time_file, 'r') as end_file: start_time_str = start_file.readline().strip() end_time_str = end_file.readline().strip() # 清理时间字符串中的额外字符和空白字符 start_time_str = start_time_str.replace('\ufeff', '').strip() end_time_str = end_time_str.replace('\ufeff', '').strip() start_time_str = start_time_str.strip() end_time_str = end_time_str.strip() # 检查时间字符串长度是否符合要求 if len(start_time_str) != len('YYYY-MM-DD HH:MM:SS') or len(end_time_str) != len('YYYY-MM-DD HH:MM:SS'): raise ValueError('时间字符串格式不正确') start_time = datetime.strptime(start_time_str, '%Y-%m-%d %H:%M:%S') end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S') return start_time, end_time
这里使用了replace函数将\ufeff(BOM)字符替换为空白字符,并使用strip函数去除字符串两端的空格。这样可以确保时间字符串不包含额外的字符或空白字符。然后再进行长度检查和解析时间字符串为datetime对象的操作。
你可以尝试运行修改后的代码,看看是否解决了问题。如果还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!   |