Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Changing month_id when looping over dates in python

I want to create a dictionary of dates where I have an id for each day, and a month id for each day in a specific month. Like:

id month_id date
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
question from:https://stackoverflow.com/questions/65843941/changing-month-id-when-looping-over-dates-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to keep track of the month and if it changes increase the month_id as below

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...