在 Python 中使用 strptime 进行时间比较

问题描述

当 service.txt 文件中的 Now() 和 datetime 之间的差异大于 25 秒时,我想进一步执行,因为我尝试了以下代码,但出现错误

service.txt:

2021-07-19 21:39:07.876953

Python 代码

then = open("service.txt","r").read()
duration = datetime.datetime.Now() - datetime.datetime.strptime(then,'%Y-%m-%d %H:%M:%s.%f')
if str(duration) > '0:00:25.0' :
    # do something

错误

Traceback (most recent call last):
   File "D:\python_projects\test.py",line 41,in <module>
    duration = datetime.datetime.Now() - datetime.datetime.strptime(then,'%Y-%m-%d %H:%M:%s.%f')
   File "C:\Python\lib\_strptime.py",line 565,in _strptime_datetime
    tt,fraction = _strptime(data_string,format)
   File "C:\Python\lib\_strptime.py",line 365,in _strptime
    data_string[found.end():]) ValueError: unconverted data remains:

解决方法

then 的值为 2021-07-19 21:39:07.876953\n
请注意末尾的换行符,您在使用 strptime 时没有考虑到这一点。

您可以通过以下方式修复它

  1. \n中用''替换then
then = open("service.txt","r").read().replace('\n','')
  1. 在日期格式字符串中包含 \n
datetime.datetime.strptime(then,'%Y-%m-%d %H:%M:%S.%f\n')
,

该文件大概在末尾包含一个换行符 \n,它包含在 read() 的返回值中。

在将其传递给 strptime 之前,您必须将其从时间戳中删除,例如使用 rstrip 方法(请参阅 How can I remove a trailing newline?):

then = open("service.txt","r").read().rstrip()