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

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

谢谢你的帮助!


当前回答

有一个高级库dateparser,可以确定给定自然语言的过去日期,并返回相应的Python datetime对象

from dateparser import parse
parse('4 months ago')

其他回答

import pandas as pd

lastmonth = int(pd.to_datetime("today").strftime("%Y%m"))-1

print(lastmonth)

202101

from datetime import date, timedelta
YYYYMM = (date.today().replace(day=1)-timedelta(days=1)).strftime("%Y%m")

你应该使用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
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

您来这里可能是因为您正在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)
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))