Implement method to retrieve last day of previous months

This commit is contained in:
George Lacey 2021-05-21 20:30:05 +01:00
parent 35c0b1946f
commit 7daaa69a62
2 changed files with 22 additions and 21 deletions

View File

@ -1,4 +1,5 @@
from datetime import datetime
import calendar
def time_ago(time: datetime, short=False, truncate=False):
@ -53,3 +54,22 @@ def subtract_months(p_date: datetime, offset):
return new_date.replace(month=12 - offset, year=new_date.year - 1)
else:
return new_date.replace(month=new_date.month - months)
def last_day_previous_months(months_ago: int):
dates = []
current_date = datetime.utcnow().date()
current_year = current_date.year
current_month = current_date.month
dates.append(current_date)
for month in range(months_ago - 1):
if current_month == 1:
current_year -= 1
current_month = 12
else:
current_month -= 1
last_day = calendar.monthrange(current_year, current_month)[1]
current_date = current_date.replace(year=current_year, month=current_month, day=last_day)
dates.append(current_date)
return dates[::-1]

View File

@ -2,11 +2,11 @@ from datetime import datetime, timedelta
from django.http import JsonResponse
from ..models import Repo
from ..utility import data
import calendar
from ..utility.time import last_day_previous_months
def repo_monthly_json(request, months_ago: int = 12):
date_labels = monthly_date_labels(months_ago)
date_labels = [date.strftime("%b %Y") for date in last_day_previous_months(months_ago)]
repo_list = Repo.objects.all()
@ -26,25 +26,6 @@ def repo_monthly_json(request, months_ago: int = 12):
return JsonResponse(response_dict)
def monthly_date_labels(months_ago: int):
dates = []
current_date = datetime.utcnow().date()
current_year = current_date.year
current_month = current_date.month
dates.append(current_date)
for month in range(months_ago - 1):
if current_month == 1:
current_year -= 1
current_month = 12
else:
current_month -= 1
last_day = calendar.monthrange(current_year, current_month)[1]
current_date = current_date.replace(year=current_year, month=current_month, day=last_day)
dates.append(current_date)
return [date.strftime("%b %Y") for date in dates][::-1]
def repo_daily_json(request, days_ago: int = 30):
repo_list = Repo.objects.all()
dates = [(datetime.utcnow() - timedelta(days=day)) for day in range(days_ago)][::-1]