start_week = start_date - datetime.timedelta(7)
end_week = start_week + datetime.timedelta(7)
while start_week < end_week:
array = np.array([])
count = CustomerProfile.objects.filter(user__date_joined__range=[start_week, end_week])
array = np.append(array, count)
start_week = end_week + datetime.timedelta(1)
end_end = start_week + datetime.timedelta(7)
这段代码效果惊人,因为我们考虑了一周的开始日期和结束日期。周将始终有7天,而一个月和一年的天数变化。我们怎样才能调整这些代码,以便它可以在数月和数年内有效地工作,而不是几周?
答案 0 :(得分:1)
您可以从今天的日期开始获取当前月份。有了它,您可以确定添加/减去的天数。
示例强>:
today = datetime.datetime.today()
current_year = today.year
current_month = today.month
daysdiff = 0
if current_month in [1, 3, 5, 7, 8, 10, 12]:
daysdiff = 31
elif current_month == 2:
# check if leap year
if current_year % 4 == 0:
if current_year % 100 == 0:
if current_year % 400 == 0:
daysdiff = 29
else:
daysdiff = 28
else:
daysdiff = 28
else:
daysdiff = 28
else:
daysdiff = 30
然后,您可以使用变量daysdiff
在进一步的计算中使用。
作为旁注,您可以使用dateutil模块,该模块具有relativedelta
方法,该方法需要数月作为参数来根据当前月份进行计算。
示例强>:
from dateutil.relativedelta import relativedelta
# as an example, lets go back one month from `now`
prev_month_date = datetime.datetime.now() - relativedelta(months=1)