在Redis中按最近30天过滤zcard的方法可以通过以下步骤来实现:
import time
current_timestamp = int(time.time())
from datetime import timedelta
thirty_days_ago = current_timestamp - timedelta(days=30).total_seconds()
redis.zremrangebyscore('your_sorted_set_key', '-inf', thirty_days_ago)
filtered_count = redis.zcard('your_sorted_set_key')
完整示例代码如下所示:
import redis
from datetime import timedelta
import time
# 连接到Redis
redis = redis.Redis(host='localhost', port=6379, db=0)
# 获取当前日期的时间戳
current_timestamp = int(time.time())
# 计算30天前的时间戳
thirty_days_ago = current_timestamp - timedelta(days=30).total_seconds()
# 删除30天前的元素
redis.zremrangebyscore('your_sorted_set_key', '-inf', thirty_days_ago)
# 获取过滤后的有序集合元素数量
filtered_count = redis.zcard('your_sorted_set_key')
print(f"过滤后的元素数量: {filtered_count}")
请注意替换代码中的 'your_sorted_set_key' 为您实际使用的有序集合的键名。