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

如何根据课程数量与指定训练日生成训练日期并写入数据库?

健身订阅训练日期生成与入库实现方案

一、核心逻辑

从指定起始日期(默认当前日期)出发,按用户选定的训练日(如周一、周三)筛选日期,收集足够数量(等于课程总数)的训练日期后,批量写入数据库。

二、分步实现

1. 训练日期生成逻辑

  • 将训练日转换为对应编程语言的星期数字标识(例如Python中datetime.weekday()返回周一=0、周日=6;Java中Calendar.DAY_OF_WEEK返回周日=1、周六=7,需注意适配)
  • 从起始日期开始逐天遍历,判断当日是否属于指定训练日,符合条件则加入结果列表,直到列表长度达到课程总数
  • 可根据业务需求决定是否包含起始日(示例默认包含起始日,若符合训练日)

2. 代码示例(Python)

使用Python标准库datetime实现日期生成:

from datetime import datetime, timedelta

def generate_training_dates(start_date, training_day_indices, total_classes):
    """
    生成训练日期列表
    :param start_date: 起始日期,datetime对象
    :param training_day_indices: 训练日索引列表,如[0,2]代表周一、周三
    :param total_classes: 课程总数
    :return: 格式化后的日期字符串列表
    """
    training_dates = []
    current_date = start_date
    while len(training_dates) < total_classes:
        if current_date.weekday() in training_day_indices:
            training_dates.append(current_date.strftime("%Y/%m/%d"))
        current_date += timedelta(days=1)
    return training_dates

# 示例调用:2023/01/01起,周一、周三共6次训练
start_dt = datetime(2023, 1, 1)
target_days = [0, 2]  # 周一=0,周三=2
result_dates = generate_training_dates(start_dt, target_days, 6)
# 输出结果:['2023/01/02', '2023/01/04', '2023/01/09', '2023/01/11', '2023/01/16', '2023/01/18']

3. 数据库批量写入

以MySQL为例,使用pymysql库实现批量插入:

import pymysql

def batch_insert_dates(subscription_id, date_list):
    """
    将训练日期批量写入数据库
    :param subscription_id: 订阅ID,关联用户订阅记录
    :param date_list: 训练日期字符串列表
    """
    db_config = {
        "host": "localhost",
        "user": "your_username",
        "password": "your_password",
        "database": "fitness_subscription"
    }
    conn = None
    cursor = None
    try:
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()
        # 构造批量插入SQL
        insert_sql = """
            INSERT INTO training_sessions (subscription_id, session_date)
            VALUES (%s, STR_TO_DATE(%s, '%Y/%m/%d'))
        """
        # 组装数据元组
        data = [(subscription_id, date_str) for date_str in date_list]
        cursor.executemany(insert_sql, data)
        conn.commit()
        print(f"成功写入{len(date_list)}条训练日期记录")
    except Exception as e:
        if conn:
            conn.rollback()
        print(f"写入失败:{str(e)}")
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()

# 调用示例
batch_insert_dates("sub_20230101_001", result_dates)

三、关键注意事项

  • 星期索引适配:不同编程语言/数据库的星期编号规则可能不同,需提前确认并调整映射关系
  • 起始日期规则:若业务要求起始日当天不算入训练次数,可将current_date初始化为start_date + timedelta(days=1)
  • 数据库字段类型:session_date建议使用DATE类型存储,避免字符串格式解析问题
  • 异常处理:需覆盖数据库连接失败、插入异常等场景,确保数据一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:15:36