微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。