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
How to Get a Directory Listing Sorted by Creation Date in Python
Reading a Utf8 CSV File with Python
Typeerror: Can't Convert 'Int' Object to Str Implicitly
Single VS Double Quotes in JSON
How to Create a Custom String Representation for a Class Object
Creating Dataframe from a Dictionary Where Entries Have Different Lengths
How to Run Multiple While Loops at a Time in Pygame
How to Turn a Python Datetime into a String, with Readable Format Date
Scope of Lambda Functions and Their Parameters
Passing an Integer by Reference in Python
Create Pandas Dataframe from Txt File with Specific Pattern
Why Python 3.6.1 Throws Attributeerror: Module 'Enum' Has No Attribute 'Intflag'
Using Python Requests with JavaScript Pages
How to Implement an Ordered, Default Dict
How to Do a Recursive Sub-Folder Search and Return Files in a List