Python 按日期范围(两个日期之间)过滤 DBF
Python filter a DBF by a range of date (between two dates)
我在 python3.5 中使用 dbf 库。
DBF table 有一列只有日期没有时间,另一列只有时间。想要检索最近五分钟的记录。
我是这个模块的新手,目前只看到两种获取存储在 DBF 中的部分数据的方法:
首先用同情SQL喜欢查询:
records = table.query("SELECT * WHERE (SA03 BETWEEN " + beforedfilter + " AND " + nowdfilter + ") AND (SA04 BETWEEN " + beforetfilter + " AND " + nowtfilter + ")")
这是一种熟悉的方法,但返回的记录是文件中的第一条记录,而不是在给定时间范围内。可能是因为模块不支持 sql 查询?或者只是我在查询中弄错了什么?另一个奇怪的是,在打印了几条记录后,我会得到一个异常:UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 3: ordinal not in range(128)
。据我所知,table.
中没有非 ascii 字符
另一种方法是使用模块的默认方式来缩小记录范围。被过滤所困,因为如果我想找到一个特定的日期和时间我可以使用它但是对于一个范围,我没有提示如何进行。
index = table.create_index(lambda rec: rec.SA03)
records = index.search(match=(?!))
最简单的方法是拥有一个只跟踪匹配记录的过滤功能:
# lightly tested
def last_five_minutes(record, date_field, time_field):
now = dbf.DateTime.now()
record_date = record[date_field]
try:
# if time is stored as HH:MM:SS
record_time = dbf.DateTime.strptime(record[time_field], '%H:%M:%S').time()
moment = dbf.DateTime.combine(record_date, record_time)
lapsed = now - moment
except (ValueError, TypeError):
# should log exceptions, not just ignore them
return dbf.DoNotIndex
if lapsed <= datetime.timedelta(seconds=300):
# return value to sort on
return moment
else:
# do not include this record
return dbf.DoNotIndex
然后使用它:
index = table.create_index(
lambda rec: last_five_minutes(rec, 'date_field', 'time_field'))
我在 python3.5 中使用 dbf 库。 DBF table 有一列只有日期没有时间,另一列只有时间。想要检索最近五分钟的记录。
我是这个模块的新手,目前只看到两种获取存储在 DBF 中的部分数据的方法:
首先用同情SQL喜欢查询:
records = table.query("SELECT * WHERE (SA03 BETWEEN " + beforedfilter + " AND " + nowdfilter + ") AND (SA04 BETWEEN " + beforetfilter + " AND " + nowtfilter + ")")
这是一种熟悉的方法,但返回的记录是文件中的第一条记录,而不是在给定时间范围内。可能是因为模块不支持 sql 查询?或者只是我在查询中弄错了什么?另一个奇怪的是,在打印了几条记录后,我会得到一个异常:UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 3: ordinal not in range(128)
。据我所知,table.
另一种方法是使用模块的默认方式来缩小记录范围。被过滤所困,因为如果我想找到一个特定的日期和时间我可以使用它但是对于一个范围,我没有提示如何进行。
index = table.create_index(lambda rec: rec.SA03)
records = index.search(match=(?!))
最简单的方法是拥有一个只跟踪匹配记录的过滤功能:
# lightly tested
def last_five_minutes(record, date_field, time_field):
now = dbf.DateTime.now()
record_date = record[date_field]
try:
# if time is stored as HH:MM:SS
record_time = dbf.DateTime.strptime(record[time_field], '%H:%M:%S').time()
moment = dbf.DateTime.combine(record_date, record_time)
lapsed = now - moment
except (ValueError, TypeError):
# should log exceptions, not just ignore them
return dbf.DoNotIndex
if lapsed <= datetime.timedelta(seconds=300):
# return value to sort on
return moment
else:
# do not include this record
return dbf.DoNotIndex
然后使用它:
index = table.create_index(
lambda rec: last_five_minutes(rec, 'date_field', 'time_field'))