You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过Unix时间戳筛选昨日新增数据?

筛选昨日新增数据的Python实现方案

直接把**日期转换为Unix时间戳(毫秒级)**来构建查询条件是最优方案——数据库中存储的就是Unix时间戳,用时间戳范围查询能利用索引提升效率,避免逐条转换数据的性能损耗。

核心思路

计算昨日00:00:00和今日00:00:00的毫秒级Unix时间戳,这两个时间点的区间就是昨日的完整时间范围,筛选created字段落在该区间内的数据即可。

完整代码示例

import datetime

# 获取本地时区的今日0点时间对象
today_start = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
# 计算昨日0点时间对象
yesterday_start = today_start - datetime.timedelta(days=1)

# 转换为数据库兼容的13位毫秒级时间戳
yesterday_start_ts = int(yesterday_start.timestamp() * 1000)
today_start_ts = int(today_start.timestamp() * 1000)

# 构建区间查询:仅包含昨日数据,排除今日
docs_all = db.collection('collection').where('created', '>=', yesterday_start_ts).where('created', '<', today_start_ts).stream()

for doc in docs_all:
    print(doc.to_dict())

时区适配说明

如果数据库中的时间戳是UTC时区,需要切换为UTC时间计算:

# UTC时区版本
today_start_utc = datetime.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
yesterday_start_utc = today_start_utc - datetime.timedelta(days=1)

yesterday_start_ts = int(yesterday_start_utc.timestamp() * 1000)
today_start_ts = int(today_start_utc.timestamp() * 1000)

内容的提问来源于stack exchange,提问作者new-to-snake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:54:55