繁体   English   中英

Python按日期范围(两个日期之间)过滤DBF

[英]Python filter a DBF by a range of date (between two dates)

我正在使用dbf库和python3.5。 DBF表有一列只包含没有时间的日期,另一列只有时间。 想要检索过去五分钟的记录。

我是这个模块的新手,目前只看到两种方法来获取存储在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) 据我所知,表中没有非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'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM