Find the end of the month Pandas DataFrame Series

后端 未结 2 1856
半阙折子戏
半阙折子戏 2020-11-28 05:55

I have a series within a DataFrame that I read in initially as an object, and then need to convert it to a date in the form of yyyy-mm-dd where dd is the end of the month.

2条回答
  •  忘掉有多难
    2020-11-28 06:17

    Agreed that root offers is the right method. However, readers who blindly use MonthEnd(1) are in for a surprise if they use the last date of the month as an input:

    In [4]: pd.Timestamp('2014-01-01')+MonthEnd(1)
    Out[4]: Timestamp('2014-01-31 00:00:00')
    
    In [5]: pd.Timestamp('2014-01-31')+MonthEnd(1)
    Out[5]: Timestamp('2014-02-28 00:00:00')
    

    Using MonthEnd(0) instead gives this:

    In [7]: pd.Timestamp('2014-01-01')+MonthEnd(0)
    Out[7]: Timestamp('2014-01-31 00:00:00')
    
    In [8]: pd.Timestamp('2014-01-31')+MonthEnd(0)
    Out[8]: Timestamp('2014-01-31 00:00:00')
    
    #Additional Example
    from pandas.tseries.offsets import MonthEnd
    # Month End of Current Time's Month in String Format
    (pd.Timestamp.now()+MonthEnd(0)).strftime('%Y-%m-%dT00:00:00')
    

提交回复
热议问题