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

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

    Here is some code to do just that. Haven't tried it out myself...

    def add_one_month(t):
        """Return a `datetime.date` or `datetime.datetime` (as given) that is
        one month earlier.
    
        Note that the resultant day of the month might change if the following
        month has fewer days:
    
            >>> add_one_month(datetime.date(2010, 1, 31))
            datetime.date(2010, 2, 28)
        """
        import datetime
        one_day = datetime.timedelta(days=1)
        one_month_later = t + one_day
        while one_month_later.month == t.month:  # advance to start of next month
            one_month_later += one_day
        target_month = one_month_later.month
        while one_month_later.day < t.day:  # advance to appropriate day
            one_month_later += one_day
            if one_month_later.month != target_month:  # gone too far
                one_month_later -= one_day
                break
        return one_month_later
    
    def subtract_one_month(t):
        """Return a `datetime.date` or `datetime.datetime` (as given) that is
        one month later.
    
        Note that the resultant day of the month might change if the following
        month has fewer days:
    
            >>> subtract_one_month(datetime.date(2010, 3, 31))
            datetime.date(2010, 2, 28)
        """
        import datetime
        one_day = datetime.timedelta(days=1)
        one_month_earlier = t - one_day
        while one_month_earlier.month == t.month or one_month_earlier.day > t.day:
            one_month_earlier -= one_day
        return one_month_earlier
    

提交回复
热议问题