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

如何判断字符串格式的给定日期是否属于最近8天的时间范围

实现步骤
  • 先把字符串格式的REFRESH转换为datetime类型,才能和时间类型变量做大小比较
  • 计算当前时间往前推8天的边界节点
  • 判断转换后的刷新时间是否落在「8天前 ~ 当前时间」的区间内,符合则返回"Pass"
完整可运行代码
from datetime import datetime, timedelta

REFRESH = "2021-11-25 00:27:23"
# 字符串转datetime对象,格式要和输入字符串完全匹配
refresh_time = datetime.strptime(REFRESH, "%Y-%m-%d %H:%M:%S")

# 获取当前时间、计算8天前的时间节点
current_time = datetime.now()
eight_days_ago = current_time - timedelta(days=8)

# 区间判断
if eight_days_ago <= refresh_time <= current_time:
    result = "Pass"
else:
    result = "Not Pass"

print(result)
补充说明

如果需求是按自然日判断(不精确到时分秒,只要日期属于近8天就算符合),可以将时间对象转为日期对象再判断,修改对应判断逻辑即可:

# 仅保留日期部分,去掉时分秒
refresh_date = datetime.strptime(REFRESH, "%Y-%m-%d %H:%M:%S").date()
current_date = datetime.now().date()
eight_days_ago_date = current_date - timedelta(days=8)

if eight_days_ago_date <= refresh_date <= current_date:
    print("Pass")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:15:03