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

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

    A variation on Duncan's answer (I don't have sufficient reputation to comment), which uses calendar.monthrange to dramatically simplify the computation of the last day of the month:

    import calendar
    def monthdelta(date, delta):
        m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
        if not m: m = 12
        d = min(date.day, calendar.monthrange(y, m)[1])
        return date.replace(day=d,month=m, year=y)
    

    Info on monthrange from Get Last Day of the Month in Python

    0 讨论(0)
  • 2020-12-02 09:47

    You can use the third party dateutil module (PyPI entry here).

    import datetime
    import dateutil.relativedelta
    
    d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
    d2 = d - dateutil.relativedelta.relativedelta(months=1)
    print d2
    

    output:

    2013-02-28 00:00:00
    
    0 讨论(0)
  • 2020-12-02 09:48

    Returns last day of last month:

    >>> import datetime
    >>> datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
    datetime.datetime(2020, 9, 30, 14, 13, 15, 67582)
    

    Returns the same day last month:

    >>> x = datetime.datetime.now() - datetime.timedelta(days=datetime.datetime.now().day)
    >>> x.replace(day=datetime.datetime.now().day)
    datetime.datetime(2020, 9, 7, 14, 22, 14, 362421)
    
    0 讨论(0)
提交回复
热议问题