How to Calculate the Date Six Months from the Current Date Using the Datetime Python Module

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

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']

Float to datetime returns wrong output (Same Month) - Python

I assumed df['tweet_creation'].loc[1] will return a number like the examples you gave.

Unfortunately, I don't know what f is, but I assumed it was a float.

My answer is inspired by this other answer: Converting unix timestamp string to readable date. You have a UNIX timestamp, so the easiest way is to use it and not convert it as a string.

from datetime import datetime, timedelta

dtobj = datetime.utcfromtimestamp(int(df['tweet_creation'].loc[1])) + timedelta(days=f-int(f))

To have the string representation you can use the function strftime.

What's the correct datetime format for this string date generated by python?

As per comment:

from datetime import datetime
print(datetime.strptime('2022-08-30T11:53:52.204219', "%Y-%m-%dT%H:%M:%S.%f"))

Result:

2022-08-30 11:53:52.204219


Related Topics



Leave a reply



Submit