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

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

    def month_sub(year, month, sub_month):
        result_month = 0
        result_year = 0
        if month > (sub_month % 12):
            result_month = month - (sub_month % 12)
            result_year = year - (sub_month / 12)
        else:
            result_month = 12 - (sub_month % 12) + month
            result_year = year - (sub_month / 12 + 1)
        return (result_year, result_month)
    
    >>> month_sub(2015, 7, 1)    
    (2015, 6)
    >>> month_sub(2015, 7, -1)
    (2015, 8)
    >>> month_sub(2015, 7, 13)
    (2014, 6)
    >>> month_sub(2015, 7, -14)
    (2016, 9)
    

提交回复
热议问题