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

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

提交回复
热议问题