Skip to content

Instantly share code, notes, and snippets.

@rg3915
Last active December 7, 2022 10:24
Show Gist options
  • Select an option

  • Save rg3915/e99e51c5bacd47dc3592 to your computer and use it in GitHub Desktop.

Select an option

Save rg3915/e99e51c5bacd47dc3592 to your computer and use it in GitHub Desktop.
Some tests with date and datetime in Django aggregation, group by day and month, vencer n dias

Some tests with date and datetime in Django

https://docs.djangoproject.com/es/1.9/topics/i18n/timezones/#troubleshooting

import datetime
from django.utils import timezone
# Return datetime now with UTC
naive = datetime.datetime.utcnow()
# Return datetime now with timezone
aware = timezone.now()
# Return today
timezone.now().day

https://docs.djangoproject.com/en/1.9/ref/models/querysets/#day

q=Subscription.objects.filter(created_at__day=22)
# Return day of date
q[0].created_at.day

from django.utils import timezone
# Return registers created at today
Subscription.objects.filter(created_at__day=str(timezone.now().day))

One day more

mydate = datetime.strptime('30/06/2016', "%d/%m/%Y") + timedelta(1)

Django aggregation, group by day

import datetime
import itertools
qs = Subscription.objects.values('created_at').values('created_at')
grouped = itertools.groupby(qs, lambda d: d.get('created_at').strftime('%Y-%m-%d'))
[(day, len(list(this_day))) for day, this_day in grouped]

http://chase-seibert.github.io/blog/2012/02/24/django-aggregation-group-by-day.html

[('2016-01-24', 7),
 ('2016-01-22', 13),
 ('2016-01-21', 5),
 ('2016-01-15', 9),
 ('2016-01-14', 1),
 ('2016-01-09', 20)]

group by month

https://code.i-harness.com/en/q/85741e

from django.db.models.functions import TruncMonth
Sales.objects
    .annotate(month=TruncMonth('timestamp'))  # Truncate to month and add to select list
    .values('month')                          # Group By month
    .annotate(c=Count('id'))                  # Select the count of the grouping
    .order_by()
from datetime import datetime
from dateutil.relativedelta import relativedelta
from random import randint
from mixer.backend.django import mixer
from django.contrib.auth.models import User
from django.db import connection


def gen_date(year=datetime.now().year):
    day = randint(1, 28)
    month = randint(1, 12)
    data = '{}-{}-{}'.format(year, month, day)
    return datetime.strptime(data, '%Y-%m-%d')

# populate db
for _ in range(100):
    mixer.blend(User, date_joined=gen_date())

# filter
users = User.objects.all()

# confere data
for user in users:
    print(user.date_joined)

# mounth count
truncate_date = connection.ops.date_trunc_sql('month', 'date_joined')
month_count = users.extra({'month': truncate_date}).values(
    'month').annotate(dcount=Count('pk')).order_by('month')

dates = []
for m in month_count:
    first_date = datetime.strptime(m['month'], '%Y-%m-%d')
    last_date = first_date + relativedelta(day=31)
    dates.append((m['dcount'], first_date.month, users.filter(
        date_joined__range=[first_date, last_date])))

for date in dates:
    print('-' * 10)
    print('Month:', date[1], '- Total:', date[0])
    for i, d in enumerate(date[2], 1):
        print(i, 'User', d)

Year

https://stackoverflow.com/a/40241868/802542

from django.db.models.functions import ExtractYear
Proposal.objects.all().annotate(Year=ExtractYear('created')).values('Year').annotate(dcount=Count('Year')).order_by()

Contratos a vencer nos próximos 5 dias

from datetime import timedelta
from django.utils import timezone

ndays = 5
start_date = timezone.now()
end_date = start_date + timedelta(ndays)
contract_list = Contract.objects.filter(date_contract__range=[start_date, end_date])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment