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

基于日期范围筛选DataFrame:查询3个月未登录用户ID

解决方法:找出过去3个月未登录的用户

步骤1:转换时间字段为可计算的datetime类型

原始的'Last Login'是字符串格式,必须先转换成pandas的datetime类型才能进行时间对比:

import pandas as pd

# 替换成你的DataFrame名称
df['Last Login'] = pd.to_datetime(df['Last Login'], format='%Y-%m-%d %H:%M:%S')

步骤2:计算3个月前的时间阈值

用当前时间减去3个月作为判断边界,这里用DateOffset处理月份计算,避免手动算天数的误差(比如2月、31天月份的问题):

three_months_ago = pd.Timestamp.now() - pd.DateOffset(months=3)

如果你的登录时间带时区,要统一时区,比如:

three_months_ago = pd.Timestamp.now(tz='UTC') - pd.DateOffset(months=3)

步骤3:筛选未登录用户

直接过滤出最后登录时间早于阈值的用户,提取'User ID'即可:

# 得到未登录用户ID的列表,方便和其他列表比对
inactive_user_ids = df[df['Last Login'] < three_months_ago]['User ID'].tolist()

# 如果需要保留DataFrame格式(仅含User ID字段)
inactive_users_df = df[df['Last Login'] < three_months_ago][['User ID']]

验证小技巧

可以打印阈值时间确认是否正确:

print(f"判断阈值:{three_months_ago.strftime('%Y-%m-%d %H:%M:%S')}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:27:29