首页 > 解决方案 > 在python中循环日期时更改month_id

问题描述

我想创建一个日期字典,其中我每天都有一个 id,并且在特定月份的每一天都有一个月份 id。像:

ID 月号 日期
1 1 2021-01-01
2 1 2021-01-02
3 1 2021-01-03
... ... ……
32 2 2021-02-01
33 2 2021-02-02

...

到目前为止,我有以下代码:

def create_date_table():
    d1 = date(2021, 1, 1)
    d2 = date(2022, 12, 31)
    delta = d2 - d1
    dates = []
    date_id = 1
    month_id = 1
    for i in range(delta.days + 1):
        full_date = (d1 + timedelta(days=i)).strftime('%Y-%m-%d')
        dates.append({'id': date_id,
                      'month_id': month_id,
                     'date': full_date})
        date_id+=1
        #increase the month_id here when month changes
    print(dates)

我不确定如何检查 for 循环中的月份何时更改。重要的是 2022 年 1 月的 month_id 应该是 13,而不是 1。任何指导将不胜感激。

标签: python

解决方案


您需要跟踪月份,如果它发生变化,请增加 month_id,如下所示

def create_date_table():
    d1 = date(2021, 1, 1)
    d2 = date(2022, 12, 31)
    delta = d2 - d1
    dates = []
    date_id = 1
    month_id = 1
    last_month = d1.month
    for i in range(delta.days + 1):
        new_date = (d1 + timedelta(days=i))
        full_date = new_date.strftime('%Y-%m-%d')
        dates.append({'id': date_id,
                      'month_id': month_id,
                     'date': full_date})
        date_id+=1
        #increase the month_id here when month changes
        if last_month != new_date.month:
            last_month = new_date.month
            month_id+=1
    print(dates)

推荐阅读