我正在尝试通过Python获取MySQL中的时间戳列表。有了清单后,我现在检查时间并检查哪些时间早于15分钟。一旦有了这些,我真的想要一个最终的总数。要实现这一目标似乎比我最初想象的要更具挑战性。
因此,我正在使用它来从MySQL获取列表:
db = MySQLdb.connect(host=server, user=mysql_user, passwd=mysql_pwd, db=mysql_db, connect_timeout=10)
cur = db.cursor()
cur.execute("SELECT heartbeat_time FROM machines")
row = cur.fetchone()
print row
while row is not None:
print ", ".join([str(c) for c in row])
row = cur.fetchone()
cur.close()
db.close()
>> 2016-06-04 23:41:17
>> 2016-06-05 03:36:02
>> 2016-06-04 19:08:56
这是我用来检查它们是否超过15分钟前的代码段:
fmt = '%Y-%m-%d %H:%M:%S'
d2 = datetime.strptime('2016-06-05 07:51:48', fmt)
d1 = datetime.strptime('2016-06-04 23:41:17', fmt)
d1_ts = time.mktime(d1.timetuple())
d2_ts = time.mktime(d2.timetuple())
result = int(d2_ts-d1_ts) / 60
if str(result) >= 15:
print "more than 15m ago"
我不知道如何将这些结合起来。另外,既然我将其写成书面形式,那么肯定有一种更容易/更好的方法来过滤这些内容吗?
感谢您的建议!
我假设heartbeat_time
字段是日期时间字段。
import datetime
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host=server, user=mysql_user, passwd=mysql_pwd, db=mysql_db, connect_timeout=10,
cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
ago = datetime.datetime.utcnow() - datetime.timedelta(minutes=15)
try:
cur.execute("SELECT heartbeat_time FROM machines")
for row in cur:
if row['heartbeat_time'] <= ago:
print row['heartbeat_time'], 'more than 15 minutes ago'
finally:
cur.close()
db.close()
如果数据量不是那么大,则将它们全部加载到内存中是一个好习惯,它将释放MySQL服务器上的内存缓冲区。对于DictCursor,两者之间没有这种区别,
rows = cur.fetchall()
for r in rows:
和
for r in cur:
它们都将数据加载到客户端。MySQLdb.SSCursor和SSDictCursor将尝试根据需要传输数据,而它需要MySQL服务器支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句