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

如何在Python中实现月度递增数值并存储月度对应关系?

月度递增的每日数值生成与存储解决方案

核心思路

无需每日对比昨日日期,直接基于当前月份计算数值,同时用字典+文件持久化存储历史月份与对应数值,确保同月份数值一致、跨月份自动递增,且数据不会丢失。

具体实现步骤

1. 数据存储设计

用字典存储键值对:

  • 键:格式化的月份名称(如"2024年5月"),确保每个月份唯一
  • 值:对应月份的数值

为避免脚本重启后数据丢失,将字典持久化到JSON文件中(替代内存存储)。

2. 数值计算逻辑

每次执行脚本时:

  1. 获取当前系统日期的月份信息
  2. 检查字典中是否已存在该月份:
    • 存在:直接返回对应的数值
    • 不存在:取已有数值的最大值加1(首次运行初始值设为1),并将新月份与数值存入字典

3. 每日执行逻辑

将脚本设置为每日定时执行(用系统定时任务工具),每次执行时自动完成数值计算与存储更新。

代码示例(Python)

import datetime
import json

# 持久化存储文件路径,可自行修改
STORAGE_FILE = "monthly_values.json"

def load_monthly_data():
    """加载已存储的月份数值数据"""
    try:
        with open(STORAGE_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        # 首次运行无文件,返回空字典
        return {}

def save_monthly_data(data):
    """将月份数值数据保存到文件"""
    with open(STORAGE_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def get_today_value():
    """获取今日对应的数值,自动处理月份更新"""
    now = datetime.datetime.now()
    current_month = now.strftime("%Y年%m月")
    monthly_data = load_monthly_data()

    if current_month in monthly_data:
        current_value = monthly_data[current_month]
    else:
        # 计算新月份的数值
        if not monthly_data:
            # 第一个月份,初始值设为1
            current_value = 1
        else:
            current_value = max(monthly_data.values()) + 1
        # 存入数据并保存
        monthly_data[current_month] = current_value
        save_monthly_data(monthly_data)
    
    return current_value, monthly_data

# 每日执行入口
if __name__ == "__main__":
    value, all_records = get_today_value()
    print(f"今日数值:{value}")
    print("所有月份记录:", all_records)

定时执行配置

  • Linux/macOS:编辑crontab(crontab -e),添加以下内容(每天凌晨0点执行):
    0 0 * * * python3 /full/path/to/your/script.py
    
  • Windows:打开「任务计划程序」,创建每日触发的任务,指定执行该Python脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:07:25