Home > Mobile >  How to filter a query according to creation date?
How to filter a query according to creation date?

Time:05-20

I have a query and I want to list the objects that created today.

query_emails = Email.objects.values('mail_from').annotate(mail_count=Count('mail_from'), mailts=F('mail_timestamp')).order_by()

mail_timestamp is the created day and it should be today, so like

.filter(mail_timestamp=today)

The output of the mail_timestamp is

'mailts': datetime.datetime(2021, 11, 8, 8, 9, 35, tzinfo=<UTC>)

I used today = datetime.now() but it didn't work.

How can I filter this type date?

CodePudding user response:

from datetime import date
date.today()

this should work

CodePudding user response:

today means that mail date have to be lower than tomorrow's 00:00:00 and bigger than yesterday's 23:59:59:

from datetime import datetime, timedelta
import pytz

from_date = (datetime.now() - timedelta(1)).replace(hour=23, minute=59, second=59, microsecond=999999, tzinfo=pytz.UTC)
to_date = (datetime.now()   timedelta(1)).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC)

# if mail_timestamp field type is Datetime:
Email.objects.filter(mail_timestamp__lt=to_date).filter(mail_timestamp__gt=from_date)

# if mail_timestamp field type is timestamp (integer representation):
Email.objects.filter(mail_timestamp__lt=datetime.timestamp(to_date)).filter(mail_timestamp__gt=datetime.timestamp(from_date))
  • Related