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

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

    Given a (year,month) tuple, where month goes from 1-12, try this:

    >>> from datetime import datetime
    >>> today = datetime.today()
    >>> today
    datetime.datetime(2010, 8, 6, 10, 15, 21, 310000)
    >>> thismonth = today.year, today.month
    >>> thismonth
    (2010, 8)
    >>> lastmonth = lambda (yr,mo): [(y,m+1) for y,m in (divmod((yr*12+mo-2), 12),)][0]
    >>> lastmonth(thismonth)
    (2010, 7)
    >>> lastmonth( (2010,1) )
    (2009, 12)
    

    Assumes there are 12 months in every year.

提交回复
热议问题