如何解析日志文件并计算花费的总时间?
How to parse a log file and calculate the total time spent?
如果日志文件与任何其他日志文件一样,则很容易解析。
但现在我有 5 个日志文件,其中包含如下数据:
Time Log:
2/23/12: 9:10pm - 11:40pm getting familiar with Flash
2/29/12: 12:50pm - 2:00pm getting familiar with Flash
3/1/12: 6:00pm - 11:40pm getting familiar with Flash
如何计算解析时间日志文件所花费的总时间?
只需使用正则表达式解析日志文件的时间,并与 datetime 模块计算差异。
请参考以下代码。
import re
import datetime
log="""2/23/12: 9:10pm - 11:40pm getting familiar with Flash
2/29/12: 12:50pm - 2:00pm getting familiar with Flash
3/1/12: 6:00pm - 11:40pm getting familiar with Flash"""
times=re.findall("(\d{1,2}:\d{1,2}[ap]m)\s*-\s*(\d{1,2}:\d{1,2}[ap]m)",log)
print(sum([datetime.datetime.strptime(t[1],"%I:%M%p")-datetime.datetime.strptime(t[0],"%I:%M%p") for t in times],datetime.timedelta()))
输出
9:20:00
如果日志文件与任何其他日志文件一样,则很容易解析。
但现在我有 5 个日志文件,其中包含如下数据:
Time Log:
2/23/12: 9:10pm - 11:40pm getting familiar with Flash
2/29/12: 12:50pm - 2:00pm getting familiar with Flash
3/1/12: 6:00pm - 11:40pm getting familiar with Flash
如何计算解析时间日志文件所花费的总时间?
只需使用正则表达式解析日志文件的时间,并与 datetime 模块计算差异。
请参考以下代码。
import re
import datetime
log="""2/23/12: 9:10pm - 11:40pm getting familiar with Flash
2/29/12: 12:50pm - 2:00pm getting familiar with Flash
3/1/12: 6:00pm - 11:40pm getting familiar with Flash"""
times=re.findall("(\d{1,2}:\d{1,2}[ap]m)\s*-\s*(\d{1,2}:\d{1,2}[ap]m)",log)
print(sum([datetime.datetime.strptime(t[1],"%I:%M%p")-datetime.datetime.strptime(t[0],"%I:%M%p") for t in times],datetime.timedelta()))
输出
9:20:00