在python中查找两个日期之间的月数

2024-06-26 02:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫数据框“df”中有一个日期对象和一个日期列“date1”,如下所示:

date = '202107'

df
    date1 
0   2021-07-01   
1   2021-08-01   
2   2021-09-01   
3   2021-10-01   
4   2021-11-01
5   2023-02-01
6   2023-03-01

我想在df中创建一列“月”,其中

months = (date1 + 1month) - date

我的输出数据框应如下所示:

df
    date1        months
0   2021-07-01   1
1   2021-08-01   2
2   2021-09-01   3
3   2021-10-01   4
4   2021-11-01   5
5   2023-02-01   20
6   2023-03-01   21

Tags: 数据对象dfdatemonthsdate1框应
3条回答

这里有一种使用熊猫的方法:

date = '202107'
date = pd.to_datetime(date, format='%Y%m')

df['months'] = (df.date + pd.offsets.MonthBegin(1)).dt.month - date.month

print(df)

        date  months
0 2021-07-01       1
1 2021-08-01       2
2 2021-09-01       3
3 2021-10-01       4
4 2021-11-01       5

给定一个日期变量,如下所示

mydate = 202003

以及包含日期时间变量start_date的数据帧[df]。你可以做:

mydate_to_use= pd.to_datetime(mydate , format = '%Y%m', errors='ignore')

df['months'] = (df['START_DATE'].dt.year - mydate_to_use.year) * 12 + (df['START_DATE'].dt.month - mydate_to_use.month)

IIUC

s=(df.date1-pd.to_datetime(date,format='%Y%m'))//np.timedelta64(1, 'M')+1
Out[118]: 
0    1
1    2
2    3
3    4
4    5
Name: date1, dtype: int64
df['months']=s

更新

(df.date1.dt.year*12+df.date1.dt.month)-(pd.to_numeric(date)//100)*12-(pd.to_numeric(date)%100)+1
Out[379]: 
0     1
1     2
2     3
3     4
4     5
5    20
6    21
Name: date1, dtype: int64

相关问题 更多 >