尝试为我的Django博客存档制作模板标签,以显示一年中的最后四个月,即:
<a>October 2017</a>
<a>September 2017</a>
<a>August 2017</a>
<a>July 2017</a>
我确定这很简单,这很愚蠢,但我只是没有得到它!这是我到目前为止所得到的:
@register.simple_tag
def last_four_months(format):
today = datetime.today()
four_months = today - relativedelta(months=4)
for month in four_months:
return four_months.strftime(format)
这会抛出TypeError - 'datetime.datetime' object is not iterable
答案 0 :(得分:1)
如果您想在一年中的最后四个月手动使用
today = datetime.today()
months = [today.replace(month=m).strftime(format) for m in range(9,13)]
返回
['September 2017', 'October 2017', 'November 2017', 'December 2017']
答案 1 :(得分:0)
您可以考虑使用dateutil.rrule
from dateutil.rrule import *
from datetime import date
months = map(
date.isoformat,
rrule(MONTHLY, dtstart=four_months, until=today)
)
您可以在此处找到更好的方法Python: get all months in range?
答案 2 :(得分:0)
请尝试以下方法......
`import datetime
def get_past_months(previos_month_count):
month_list=[]
today = datetime.date.today()
first = today.replace(day=1)
last_month = first - datetime.timedelta(days=1)
month_list.append(last_month.strftime("%Y-%m"))
for i in range(1, previos_month_count):
first = last_month.replace(day=1)
last_month = first - datetime.timedelta(days=1)
month_list.append(last_month.strftime("%Y-%m"))
return month_list`