What's the simplest way to subtract a month from a date in Python?

前端 未结 21 1933
[愿得一人]
[愿得一人] 2020-12-02 09:12

If only timedelta had a month argument in it\'s constructor. So what\'s the simplest way to do this?

EDIT: I wasn\'t thinking too hard about this as was poin

21条回答
  •  清歌不尽
    2020-12-02 09:32

    I use this for government fiscal years where Q4 starts October 1st. Note I convert the date into quarters and undo it as well.

    import pandas as pd
    
    df['Date'] = '1/1/2020'
    df['Date'] = pd.to_datetime(df['Date'])              #returns 2020-01-01
    df['NewDate'] = df.Date - pd.DateOffset(months=3)    #returns 2019-10-01 <---- answer
    
    # For fun, change it to FY Quarter '2019Q4'
    df['NewDate'] = df['NewDate'].dt.year.astype(str) + 'Q' + df['NewDate'].dt.quarter.astype(str)
    
    # Convert '2019Q4' back to 2019-10-01
    df['NewDate'] = pd.to_datetime(df.NewDate)
    

提交回复
热议问题