我正在尝试为使用情况统计信息生成一个报告。下面是我在数组中的示例数据,这是从Mysql表中获取的。如何实现一个逻辑,说明如果用户空闲时间超过30分钟他没有使用系统,否则计算使用时间的平均时间。
timestamp=[]
for i in timestamp:
print i
2010-04-20 10:07:30
2010-04-20 10:07:38
2010-04-20 10:07:52
2010-04-20 10:08:22
2010-04-20 10:08:22
2010-04-20 10:09:46
2010-04-20 10:10:37
2010-04-20 10:10:58
2010-04-20 10:11:50
2010-04-20 10:12:13
2010-04-20 10:12:13
2010-04-20 10:25:38
2010-04-20 10:26:01
2010-04-20 10:26:01
2010-04-20 10:26:06
2010-04-20 10:26:29
2010-04-20 10:26:29
2010-04-20 10:26:35
2010-04-20 10:27:21
2010-04-20 01:32:46
2010-04-20 01:32:47
2010-04-20 01:32:57
2010-04-20 01:32:59
2010-04-20 01:33:03
2010-04-20 01:33:03
2010-04-20 01:33:05
2010-04-20 01:33:11
2010-04-20 01:33:15
2010-04-20 01:34:49
2010-04-20 01:34:55
2010-04-20 01:35:02
2010-04-20 01:35:17
2010-04-20 01:35:20
2010-04-20 01:36:49
2010-04-20 01:36:52
2010-04-20 01:36:52
2010-04-20 01:37:11
2010-04-20 01:37:15
2010-04-20 01:37:17
2010-04-20 01:50:11
2010-04-20 01:50:15
2010-04-20 01:50:18
2010-04-20 01:50:20
2010-04-20 01:50:33
2010-04-20 01:50:36
2010-04-20 01:51:56
答案 0 :(得分:4)
我认为这就是你想要的。它通过列表计算每个条目和前一个条目之间的差异。如果差异大于或等于30分钟,则忽略它。如果小于30分钟,则将其添加到该用户的总使用量中。 (我假设所有时间戳都是针对同一个用户的。)
from datetime import datetime,timedelta
# Convert the timestamps to datetime objects
usetimes = sorted(datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in timestamp)
# Set the idle time to compare with later
idletime = timedelta(minutes = 30)
# Start the running total with a timedelta of 0
usage = timedelta()
last = usetimes[0]
for d in usetimes[1:]:
delta = d - last
if delta < idletime:
usage += delta
last = d
print "total usage:",usage
如果你想使用sum()
和zip()
,你可以减少代码行,但我不确定它是否可读:
from datetime import datetime,timedelta
usetimes = sorted(datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in timestamp)
idletime = timedelta(minutes = 30)
usage = sum((x - y for x,y in zip(usetimes[1:],usetimes[:-1]) if x - y < idletime),timedelta())
print "total usage:", usage
在这种情况下,如果时间戳列表很长,您可以考虑使用izip
中的itertools
而不是zip
。