pandas获取指定日期所属月的月初月末

本文介绍如何使用Python的Pandas库进行日期格式转换,并演示了如何获取月初、月末及跨月日期的方法。通过具体实例展示了不同日期操作的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd
from pandas.tseries.offsets import MonthBegin, MonthEnd  
from datetime import datetime as dt
# 日期格式为yyyy-mm-dd
df1 = pd.DataFrame({'date': ['2022-01-01', '2022-02-15', '2022-03-02', '2022-05-31']})
df1['new_date'] = df1['date'].astype('datetime64')

'''
# 日期格式为yyyy-mm-dd hh-mm-ss
f1 = pd.DataFrame({'date': ['2022-01-01 11:10:00', '2022-02-15 12:45:00']})
df1['new_date'] = df1['date'].astype('datetime64').dt.date 
'''

# 本月初:将间隔参数n设置成0时,当仅为月初日期时才能正确的获取当月月初日期,其余日期将获取成下月月初日期
df1['MonthStart'] = df1['new_date'] + MonthBegin(n=1) -  MonthBegin(n=1)

'''
# 方法2
def get_month_start(x):
    return datetime(x.year, x.month, 1)
df1['MonthStart'] = df['new_date'].map(get_month_start)
'''
# 本月末
df1['monthend'] = df1['new_date'] + MonthEnd(n=0) # n默认为1

# 下月月末
df1['last_MonthEnd'] = df1['new_date'] + MonthEnd(n=0) +  MonthEnd(n=1)

print(df1)

       date   new_date MonthStart   monthend last_MonthEnd
0  2022-01-01 2022-01-01 2022-01-01 2022-01-31    2022-02-28
1  2022-02-15 2022-02-15 2022-02-01 2022-02-28    2022-03-31
2  2022-03-02 2022-03-02 2022-03-01 2022-03-31    2022-04-30
3  2022-05-31 2022-05-31 2022-05-01 2022-05-31    2022-06-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值