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

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

提交回复
热议问题