我试图用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)

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

谢谢你的帮助!


当前回答

你应该使用dateutil。 有了它,你可以使用relativedelta,它是timedelta的改进版本。

>>> import datetime 
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relativedelta(months=-1)
2012-02-15 12:33:04.281248

其他回答

在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

from datetime import date, timedelta

first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)

print "Previous month:", last_day_of_previous_month.month

Or:

from datetime import date, timedelta

prev = date.today().replace(day=1) - timedelta(days=1)
print prev.month

Datetime和Datetime。Timedelta类是您的朋友。

今天发现。 用这个找到这个月的第一天。 使用timedelta将某一天备份到上个月的最后一天。 打印您正在寻找的YYYYMM字符串。

是这样的:

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 last_month = first - datetime.timedelta(days=1)
 print(last_month.strftime("%Y%m"))
 

201202打印出来了。

from datetime import datetime, timedelta, time, timezone

current_time = datetime.now(timezone.utc)
last_day_previous_month = datetime.combine(current_time.replace(day=1), time.max) - timedelta(days=1)
first_day_previous_month = datetime.combine(last_day_previous_month, time.min).replace(day=1)

输出:

first_day_previous_month: 2022-02-01 00:00:00 
last_day_previous_month: 2022-02-28 23:59:59.999999

您来这里可能是因为您正在NiFi中使用Jython。这就是我最终实现它的方式。我稍微偏离了Robin Carlo Catacutan的答案,因为访问last_day_of_prev_month。由于这里解释的Jython数据类型问题,由于某种原因,这个问题似乎存在于NiFi的Jython中,但不存在于vanilla Jython中。

from datetime import date, timedelta
import calendar
    
flowFile = session.get()
    
if flowFile != None:

    first_weekday_in_prev_month, num_days_in_prev_month = calendar.monthrange(date.today().year,date.today().month-1)

    last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
    first_day_of_prev_month = date.today().replace(day=1) - timedelta(days=num_days_in_prev_month)
            
    last_day_of_prev_month = str(last_day_of_prev_month)
    first_day_of_prev_month = str(first_day_of_prev_month)
    
    flowFile = session.putAllAttributes(flowFile, {
        "last_day_of_prev_month": last_day_of_prev_month,
        "first_day_of_prev_month": first_day_of_prev_month
    })
    
session.transfer(flowFile, REL_SUCCESS)