按月遍历日期范围



我有一个包含datetime作为列的Pandas DataFrame。我希望每个月都重复一遍。目前,我可以使用'pandas.query()'使用硬代码对其进行切片,如下所示:

# For January 2018-
data_jan = data.query("opened_at >= '2018-01-02 00:00:00' and opened_at <= '2018-01-31 23:59:59'")

然而,为了每个月迭代,我正在寻找一个代码。到目前为止,我的代码是:

delta = timedelta(days = 30, hours = 0, minutes = 0, seconds = 0)
while start_date <= end_date:
print(start_date.strftime("%Y-%m-%d"))
start_date += delta

但是,while循环给出错误:

TypeError: can't compare datetime。Datetime到Datetime .date

帮助吗?

对于按月分组的Series.dt.to_period,可以使用月周期:

months = df['opened_at'].dt.to_period('m')
for month, g in df.groupby(months):
print (g)

最新更新