我试图用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)
我还没有测试这段代码,我不想使用它(除非我找不到任何其他方法:/)
谢谢你的帮助!
基于bgporter的回答。
def prev_month_range(when = None):
"""Return (previous month's start date, previous month's end date)."""
if not when:
# Default to today.
when = datetime.datetime.today()
# Find previous month: https://stackoverflow.com/a/9725093/564514
# Find today.
first = datetime.date(day=1, month=when.month, year=when.year)
# Use that to find the first day of this month.
prev_month_end = first - datetime.timedelta(days=1)
prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
# Return previous month's start and end dates in YY-MM-DD format.
return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))
基于@ 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
对于那些来到这里,并希望获得前一个月的第一天和最后一天的人:
from datetime import date, timedelta
last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)
输出:
First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28
您来这里可能是因为您正在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)
明确的方式:
import datetime
result = (datetime.datetime.today().month - 2) % 12 + 1
问题是如何将月[1,2,3,…], 12]到[12,1,2,…]11)。
Step1: month = month - 1转移[1,2,3,…], 12] to[0,1,2,…]11)。
Step2: month = (month - 1) % 12 transfer[0,1,2,…], 11] to[11, 0,1,…], 10]。
Step3: month = month + 1 transfer[11, 0, 1,…], 10]到[12,1,2,…]11)。
因此,结果是result =(月- 2)% 12 + 1
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