我试图用python获取前一个月的日期。 以下是我的尝试:

str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )

然而,这种方式有两个原因:首先,它将返回2012年2月的20122(而不是201202);其次,它将返回0而不是1月的12。

我一下子就解决了这个麻烦

echo $(date -d"3 month ago" "+%G%m%d")

我认为,如果bash有一种内置的方式来实现这一目的,那么python应该提供更好的东西,而不是强迫自己编写脚本来实现这一目标。当然我可以这样做:

if int(time.strftime('%m')) == 1:
    return '12'
else:
    if int(time.strftime('%m')) < 10:
        return '0'+str(time.strftime('%m')-1)
    else:
        return str(time.strftime('%m') -1)

我还没有测试这段代码,我不想使用它(除非我找不到任何其他方法:/)

谢谢你的帮助!


当前回答

def prev_month(date=datetime.datetime.today()):
    if date.month == 1:
        return date.replace(month=12,year=date.year-1)
    else:
        try:
            return date.replace(month=date.month-1)
        except ValueError:
            return prev_month(date=date.replace(day=date.day-1))

其他回答

这很简单。这样做

from dateutil.relativedelta import relativedelta
from datetime import datetime

today_date = datetime.today()
print "todays date time: %s" %today_date

one_month_ago = today_date - relativedelta(months=1)
print "one month ago date time: %s" % one_month_ago
print "one month ago date: %s" % one_month_ago.date()

输出如下: 美元python2.7 main.py

todays date time: 2016-09-06 02:13:01.937121
one month ago date time: 2016-08-06 02:13:01.937121
one month ago date: 2016-08-06

基于@ j.f.的评论。Sebastian,您可以将replace()函数链接到一个“月”之前。因为一个月不是一个固定的时间段,所以这个解决方案尝试返回到前一个月的同一日期,当然这并不适用于所有月份。在这种情况下,该算法默认为前一个月的最后一天。

from datetime import datetime, timedelta

d = datetime(2012, 3, 31) # A problem date as an example

# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
    # try to go back to same day last month
    one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
    pass
print("one_month_ago: {0}".format(one_month_ago))

输出:

one_month_ago: 2012-02-29 00:00:00

简单,一行代码:

import datetime as dt
previous_month = (dt.date.today().replace(day=1) - dt.timedelta(days=1)).month

你可以这样做:

from datetime import datetime, timedelta    
last_month = (datetime.now() - timedelta(days=32)).strftime("%Y%m")

在Pendulum非常完整的库中,我们有了subtract方法(而不是“subact”):

import pendulum
today = pendulum.datetime.today()  # 2020, january
lastmonth = today.subtract(months=1)
lastmonth.strftime('%Y%m')
# '201912'

我们看到它处理跳跃的年份。

相反的等效形式是add。

https://pendulum.eustace.io/docs/#addition-and-subtraction