How to get last six month data from date field - django - python

I do have a model as below
class Employee(models.Model):
employee_name = models.CharField(max_length=100)
joining_Date = models.DateField(blank=False, null=False)
I want to get data for last six months (including current month) joined employee count month wise.
Example:
July : 12,
June : 10,
May : 8,
April : 16,
March : 13,
February : 10,
joining_Date stores data like "2022-07-22". How to get done this by having date field?

To get the count of new employees per month you will need to annotate and use Trunc to just get the month, see below:
from datetime import date
from dateutil.relativedelta import relativedelta
from django.db.models.functions import Trunc
six_months_ago = date.today() + relativedelta(months=-6)
employees_per_month = Employee.objects.filter(join_date__gte=six_months_ago)\
.annotate(
joining_month=Trunc('joining_date', 'month', output_field=DateField())
) \
.order_by('joining_month') \
.values('joining_month') \
.annotate(employees=Count('joining_month'))
This will give you a queryset with the following structure:
<QuerySet [{'joining_month': datetime.date(2022, 6, 1), 'employees': 2},
{'joining_month': datetime.date(2022, 7, 1), 'employees': 1}, ...
Edit
To convert the QS into a flat dict:
employee_count_dict = {}
for employee_count in employees_per_month:
employee_count_dict[val['joining_month']] = val['employees']

You can try to find maximum apropriate date, and filter by it
from datetime import date
from dateutil.relativedelta import relativedelta
def find_employee(request):
today = date.today()
six_months = today - relativedelta(months=6)
emloyed_for_six_month = Employee.objects.filter(joining_Date__gte = six_months)
Your employee model should be named with a capital letter. It is conventional
https://stackoverflow.com/a/386054/14632651

Related

Django query to filter date range

I have a model which contains date range i want to filter the data based on the range date
that is i want the data who's date range is 90 days from today's date.
class MyModel(models.Model):
name = models.CharField(max_length=255)
start_end_date = ranges.DateTimeRangeField(validators=
[validate_range_date_time])
so when we select the start date on page the end date will popoulate the same date but i cannot concatenate filter just by today date + timedelta(days=90) this is one single date and the field is date range, so how can i filter the date range data which is 90 days from now.
the model stores start_end_date as
'start_end_date': DateTimeTZRange(datetime.datetime(2022, 11, 29, 9, 15), datetime.datetime(2022, 11, 29, 10, 0),
Mymodel.objects.filter(start_end_date__contains=timezone.now() + timezone.timedelta(days=90))
timezone.now() + timezone.timedelta(days=90) = datetime.datetime(2022, 11, 29, 22, 52, 7, 759648)
the query is giving empty set
I think you could design the model more easily.
class MyModel(models.Model):
name = models.CharField(max_length=255)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
Then you can find objects like the following.
target_time = timezone.now() + timezone.timedelta(days=90)
MyModel.objects.filter(start_date__lte = target_time).filter(end_date__gte = target_time)
As it's a DateTimeRangeField, I think your result can be achieved by using startswith and endswith just like that:
max_date = timezone.now() + timezone.timedelta(days=90)
MyModel.objects.filter(start_end_date__startswith__gte=timezone.now(), start_end_date__endswith__lte=max_date)
Hope it helps!
I haven't used this field myself, but in base of what i read from documentaition, it should be like this:
from psycopg2.extras import DateTimeTZRange
Mymodel.objects.filter(
start_end_date__contained_by=DateTimeTZRange(
timezone.now(),
timezone.now() + timezone.timedelta(days=90)
)
)
to check if any start_end_date field is in 90 days from now, you should also pass a datetime range.
edited:
from psycopg2.extras import DateTimeTZRange
Mymodel.objects.filter(
start_end_date__contained_by=DateTimeTZRange(
timezone.now(),
timezone.now() + timezone.timedelta(days=90),
start_end_date__lower_inc=False
)
)

first and last methods used excluded items

i used last() to get last item of queryset after exclude some items as below:
holidays = HolidayModel.objects.all().values_list('date', flat=True)
result = BorseExchangeLog.objects.exclude(
hint_time__date__in=holidays
)
# output 1
print(list(result.valuse_list('hint_time__date',flat=True).distinct('hint_time__date')))
#output2
print(result.last().hint_time.date())
but in output2 print item that not exists in output1
i test some other codes as below:
print(list(logs.values_list('hint_time__date',flat=True).distinct('hint_time__date')))
print(list(logs.values_list('hint_time__date', flat=True).distinct('hint_time__date'))[-1])
print(logs.order_by('hint_time__date').last().hint_time.date())
[..., datetime.date(2020, 10, 21), datetime.date(2020, 10, 26)]
2020-10-26
2020-10-25
my holiday model:
class HolidayModel(models.Model):
creator = models.ForeignKey('accounts.Account', on_delete=models.PROTECT, verbose_name=_('Creator'))
reason = models.CharField(default='', max_length=200, verbose_name=_('Reason'))
date = models.DateField(default=timezone.now, verbose_name=_('Date'))
and other model is :
class BorseExchangeLog(models.Model):
create_time = models.DateTimeField(default=timezone.now)
hint_time = models.DateTimeField(default=timezone.now)
i test that by first() and problem was there too
what is problem? my code is wrong or bug from django orm?
using django2.2 and postgresql
Your datetimes are timezone aware but the date() method on datetime objects does not take the timezone into account, __date will take the timezone into account provided your DB supports it. Use the django.utils.timezone.localdate function to get a date taking into account the timezone
from django.utils.timezone import localdate
print(localdate(result.last().hint_time))

How to pass multiple strike prices or range of strike prices when downloading data with nsepy in python

I want to download the data in one go for multiple strike prices. Below function works as expected but for single strike price.
def download_nifty_option_data(self):
expiry_date_prev_month = get_expiry_date(year=2018, month=11)
#Adding one day
expiry_date_prev_month = expiry_date_prev_month + datetime.timedelta(days=1)
expiry_date_this_month = get_expiry_date(year=2018, month=12)
print expiry_date_this_month
date1 = datetime.datetime.strptime(str(expiry_date_prev_month), "%Y-%m-%d")
date2 = datetime.datetime.strptime(str(expiry_date_this_month), "%Y-%m-%d")
nifty_opt = get_history(symbol="NIFTY",
start=date(date1.year, date1.month, date1.day),
end=date(date2.year, date2.month, date2.day),
index=True,
option_type='CE',
strike_price=10900,
expiry_date=date(2018, 12, 27))
#nifty = get_history(symbol="NIFTY", start=date(2015, 1, 1), end=date(2018, 12, 13), index=True)
nifty_opt.to_csv(self.download_dir + 'nifty_opt.csv', index=True)
print 'Data downloaded successfully!'
Is there any way to pass multiple strike prices? I am following this link but couldn't solution there.

Sorting queryset with date

Extending from the question here, where queryset is filtered using input from the user, I wanted to know if it was possible to filter queryset depending on present month and week. Eg each month should start on the 1st and each week on a monday and the queryset should be filtered for all the tests that have taken place in the present month and week.
models.py
class City(models.Model):
city_name=models.CharField(max_length=100,default='',blank=False)
class Person(models.Model):
title = models.CharField(max_length=3,default="mr",blank=False)
name = models.CharField(max_length=50,default='',blank=False)
address = models.CharField(max_length=200,default='',blank=False)
city = models.ForeignKey(City)
class Test(models.Model):
person = models.ForeignKey(Person)
date = models.DateTimeField(auto_now_add=True)
test_name = models.CharField(max_length=200,default='',blank=False)
subject = models.CharField(max_length=100,default='')
views.py
def personlist(request, id):
data = requests.get('http://127.0.0.1:8000/app/cities/' + id + '/persons/').json()
context = RequestContext(request, {
'persons': data['results'],'count': data['count'],
})
return render_to_response('template.html', context)
And the related json
According to this question - one way could be to use
startdate = date.today()
enddate = startdate + timedelta(days=6)
Sample.objects.filter(date__range=[startdate, enddate])
But wouldn't date.today() keep changing everyday and thus everyday a new week will start and thus, a new queryset?Similarly with month. Is there a way to get querysets filtered by present week and month. With each starting from every monday and every 1st respectively?
You can use the __month and __year lookups to limit the queryset to this month's objects.
from datetime import date
today = date.today()
this_month_qs = Sample.objects.filter(
date__month=today.month,
date_year=today.year,
)
To find this weeks objects, you first need to find the date of this Monday. You can do this by finding today's day of the week (Monday = 0, Sunday = 6) using a date's weekday() method, and subtracting that many days from today. It's easy to calculate the last day of the week by adding 6 days, and then you can use __range to find this week's objects.
from datetime import date, timedelta
today = date.today()
# Use today.isoweekday() if you want the week
# to start on Sunday instead of Monday
first_day_of_week = date.today() - timedelta(today.weekday())
end_date = first_day_of_week + timedelta(days=6)
this_week_qs = Sample.objects.filter(date__range=[startdate, enddate])

how can i get the right datetime info to the user registered date in django?

i create a website using django .and now i want show the number of users registered today,
so i write this code
from django.utils import timezone
from django.contrib.auth import get_user_model
um=get_user_model()
now=timezone.now()
todayusers=um.objects.filter(date_joined__day=now.day,date_joined__month=now.month,date_joined__year=now.year).count()
today it is 4th july 2014 ,and i find today mywebsite get two users registered
but it show todayusers =0
i do not knwo why ?
so i change the code to make it simple
todayusers=um.objects.filter(date_joined__day=4).count()
it show todayusers=0
and i change it to
todayusers=um.objects.filter(date_joined__day=3).count()
ok ,this time ,it show todayusers=2
i find one of the user ,its user id is 13,so i get that user
u13=um.objects.get(ud=13)
now i check its date_joined ,this datetime filed
u13.date_joined.day=4
that means ,it should be 4th july ,why when i query it in django ,it can not find
my django TIME_ZONE = 'Asia/Shanghai'
any one can help me
See if this works
todayusers=um.objects.filter(date__year='2014',
date__month='07', date__day='04').count()
OR
start_date = datetime.date(2014, 7, 4)
end_date = datetime.date(2014, 7, 4)
todayusers = um.objects.filter(date__range=(start_date, end_date)).count()
OR
todayusers = um.objects.filter(date__gte=datetime.datetime.today()).count()
OR
from pytz import timezone
from datetime import datetime
asia_sh = timezone("Asia/Shanghai")
startdate = datetime(2014, 07, 04, 0, 0, 0, tzinfo=asia_sh)
enddate = datetime(2014, 07, 04, 23, 59, 59, tzinfo=aisa_sh)
todayusers = um.objects.filter(date__range=(start_date, end_date)).count()

Categories

Resources