python - 在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。任何指导将不胜感激。
解决方案
您需要跟踪月份,如果它发生变化,请增加 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)
推荐阅读
- asp.net-core - Razor 视图中的三元字符串比较不起作用
- php - Docker 无法连接到特定端口上的主机
- flutter - 如何在颤动中将滚动视图放在堆栈小部件中
- python - 如何通过回调函数将一个 Bokeh 小部件的输出用作另一个小部件的输入?
- sql - 如何循环一次删除一行
- excel - 如何将向量传递给Excel vba中的数组中的一行?
- css - 如何在不删除 Firefox/IE 上的轮廓焦点的情况下自定义输入边框
- angular - Angular 7 WebSocketSubject。订阅路径
- ios - 需要查找用户手动拖动或自动对焦更改的mapView区域
- java - HTTP 状态 400 错误请求