python - 计算文本文件中的时间与现在的时间差

标签 python python-2.7 datetime text-processing strptime

我是 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; if f.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/

相关文章:

python - 如何将 Flask/WTForms SelectField 添加到我的 HTML 中?

python - jupyter notebook 显示 matplotlib Bad key "text.kerning_factor"的错误消息

python - 不同IDE的除法结果不同

c# - 检查指定日期何时发生的最佳方法

python - 使用已应用的迁移应用南迁移

python - 使用 matplotlib.ticker 设置 Matplotlib Ytick 标签会产生关键错误

python - 是否可以在 Django 上使用 Python SpeechRecognition?

python - 有没有办法在 Python 中对 1900 年之前的日期使用类似 strftime 的函数?

java - "DateUTC"最准确的 joda-time 表示是什么?

python lambda打印空间