我是 Python 新手,正在编写一个简单的脚本来计算写入文本文件的时间与现在之间的时间差。文本文件中时间的格式为:2013-10-05 00:20
这是脚本
f = open('N:\\newfile.txt')
timestamp = f.readline()
f.close()
now = str(datetime.now())
#Removing the seconds from the now time
now = now[0:16]
FMT = '%Y-%m-%d %H:%M'
tdelta = datetime.strptime(now, FMT) - datetime.strptime(timestamp, FMT)
print tdelta
但是当我运行它时,出现以下错误
Traceback (most recent call last):
File "N:\Test.py", line 12, in <module>
tdelta = datetime.strptime(now, FMT) - datetime.strptime(timestamp, FMT)
File "C:\Program Files (x86)\Python26\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
有人可以建议我做错了什么吗?
最佳答案
文件对象的 readline()
方法返回一行包括它的终止换行符。 Python的文档有the details :
f.readline()
reads a single line from the file; a newline character (\n
) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; iff.readline()
returns an empty string, the end of the file has been reached, while a blank line is represented by'\n'
, a string containing only a single newline.
所以,您的时间戳
看起来像这样:
'2014-06-18 23:33\n'
... 和 strptime()
在最后的换行符上令人窒息。您可以通过更改此行来修复它:
timestamp = f.readline()
至
timestamp = f.readline().strip()
(使用 str.strip()
方法从字符串中去除空格)。
关于python - 计算文本文件中的时间与现在的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24297932/