Arefe Arefe - 6 months ago 8
Python Question

How to find all the dates within last 6 months using Python ?

I'm doing queries find all the dates within last 6 months using Python and SQLAlchemy. The code is as following,

current_time = datetime.datetime.utcnow()
six_months_ago = current_time - datetime.timedelta(weeks = 24)
puppies = session.query(Puppy).filter(Puppy.dateOfBirth > six_months_ago).all()

for puppy in puppies:
puppy.name, puppy.dateOfBirth


Now, how do I use month's directly in the code than using weeks ? I have seen an elegant solution, but, that uses an external library. I would like to do this w/o installing another library.

hd1 hd1
Answer

You'll need to use python-dateutil:

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

There doesn't appear to be a way to do this with the out-of-the-box tools.

Comments