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

标签 python pandas

我在 pandas 数据框“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 where 中创建一列“月份”

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

最佳答案

这是使用 pandas 的方法:

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

关于python - 在python中查找两个日期之间的月数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515599/

相关文章:

python - scipy.io.wavfile.read 无法读取 24 位 .wav 文件

python - 如何获取我的python3.4中的unicode版本?

python - Flask-上传 : how to use with application factory

python - Matplotlib:随时间叠加多个二维箭袋图

python - 根据索引将大型数据框中的数据除以较小数据框中的数据

python - 使用正则表达式从 Pandas 数据框中的列中提取数据

python - 如何查看str包含bool数组的内容?

python - Pandas Dataframe检查id在时间间隔内是否出现大于1

python - 导入 tkinter 重复打印输出

Python - 保留日期列并使用字段名称翻转单元格