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

MongoDB指定月份日期范围查询异常求助(Python实现)

问题解决:MongoDB查询指定月份数据的代码修正

代码中的核心问题

  1. 变量名不匹配:你定义了last_of_month但查询时使用了未定义的end_of_month,直接导致运行报错。
  2. 日期范围逻辑错误:即便修正变量名,用当月最后一天的0点作为$lt条件,会漏掉当月最后一天中所有时间大于0点的记录(比如2024-05-31 14:30:00这类数据)。

修正后的代码实现

正确的做法是用当月第一天0点作为起始条件,下个月第一天0点作为结束条件,完整覆盖指定月份的所有数据:

import datetime
import calendar

# 假设year和month为已定义的目标年月,如year=2024, month=5
start_of_month = datetime.datetime(year, month, 1, 0, 0, 0)

# 计算下个月第一天作为结束时间
if month == 12:
    end_of_month = datetime.datetime(year + 1, 1, 1, 0, 0, 0)
else:
    end_of_month = datetime.datetime(year, month + 1, 1, 0, 0, 0)

# 也可使用dateutil库简化计算(需先执行pip install python-dateutil)
# from dateutil.relativedelta import relativedelta
# end_of_month = start_of_month + relativedelta(months=1)

# 最终查询语句
query = {"date": {"$gte": start_of_month, "$lt": end_of_month}}

逻辑说明

  • $gte: start_of_month:匹配所有日期大于等于当月第一天0点的记录
  • $lt: end_of_month:匹配所有日期小于下个月第一天0点的记录,确保包含当月最后一天的所有时间点数据

内容的提问来源于stack exchange,提问作者Suganth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 04:04:59