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

前端 未结 21 1888
[愿得一人]
[愿得一人] 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:44

    You can use below given function to get date before/after X month.

    from datetime import date
    
    def next_month(given_date, month):
        yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)
        mm = int(((given_date.year * 12 + given_date.month) + month)%12)
    
        if mm == 0:
            yyyy -= 1
            mm = 12
    
        return given_date.replace(year=yyyy, month=mm)
    
    
    if __name__ == "__main__":
        today = date.today()
        print(today)
    
        for mm in [-12, -1, 0, 1, 2, 12, 20 ]:
            next_date = next_month(today, mm)
            print(next_date)
    

提交回复
热议问题