Django: Filter objects by date range - python

My object model is :
class Event(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()
I need to filter all objects for today.
I have one object with start date 2014/03/01 00:00 and end date 2014/10/01 00:00.
I need to have this object when filtering objects by today date ex.:
Event.objects.filter(start__gte=today, end__lte=today)
How can I filter objects by today date and get all results where start > today < end ?

Get the today's date from datetime.date.today() and use gt and lt:
import datetime
today = datetime.date.today()
Event.objects.filter(start__lt=today, end__gt=today)
This would filter objects where start date is less than today and end date is greater than today.

You can use combine method of datetime module:
import datetime
today = datetime.datetime.today()
Event.objects.filter(start__gte=datetime.datetime.combine(today, datetime.time.min),
end__lte=datetime.datetime.combine(today, datetime.time.max))

Related

How to get the number of days by subtraction from the datetime field and then filter in Django?

This is model:
class Work(models.Model):
start_date = DateTimeField()
end_date = DateTimeField()
sot = IntegerField(help_text='days')
I want to subtract the start time from the end time to get the number of days to compare with sot and filter out the data I want.
I can get what I want through the loop, but this is very inelegant, is there any way to do it through ORM?
[w for w in Work.objects.all() if (w.end_date - w.start_date).days < w.sot ]
You can use F expiression
Use F to reference field end_date and start_date
Subtract start_date from end_date, which give a timestamp difference in microseconds.
Convert the timestamp difference in microseconds to days
Filter the day difference with sot field
Work.objects.filter(sot__gt=(F('end_date')-F('start_date'))/(3600*24*1000*1000))

How to define date range and assign it to a variable in python

I need to amend an existing python sript which extracts data from previous day to extract data for last two weeks like biweekly data. Please advise how I can twik to get the date range in the variable
def parse_gov():
reject_patterns = generate_reject_patterns()
today_str = date.today().strftime('%Y.%m.%d')
yesterday =
yesterday_str = yesterday.strftime('%Y.%m.%d')
query_date = date.today()
So need to get the date range in yesterday variable
You can use timedelta to do so. for example,
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)

Check date is within one year python

I have a date string formatted like this: "2017-05-31T06:44:13Z".
I need to check whether this date is within a one year span from today's date.
Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.
from datetime import datetime
from dateutil.relativedelta import relativedelta
# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)
if today <= date_to_check <= one_year_from_now:
# do whatever
Use the datetime package together with timedelta:
import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)
and simply check if now-d > then.

Save old dates and display time until next anniversary of that date in Django

I'm trying to write a basic reminder app where users can enter important dates (birthdays, anniversaries, etc.) and see how much time is left until the next anniversary of that date. For example, a user can have a birthday as something like Jan 1st 1990, and I want to display for them the time until their next birthday (2 months 14 days).
I've been using the django timeuntil built in template tag, but it only works for dates in the future (it won't display anything if the date is before the current date). I'm not sure how to to go about "normalizing" the entered date to be a time in the future.
Current code:
def events(request):
relationships = Relationship.objects.filter(user=request.user)
events = Event.objects.filter(user=request.user).order_by('date')[:8]
event_date = events[0].date
if datetime.now() >= event_date:
difference = datetime.now() - event_date
event_date_new = event_date + difference
event_date = event_date_new
context = {
'relationships': relationships,
'events': events
}
return render(request, 'app/events.html', context)
Template
<td class="column-right"><h4>{{event.date|timeuntil}}</h4></td>
(It also throws an error on datetime.now() module has no attribute "now", is that an old way to find the current date?)
Thanks in advance!
now is a method of the datetime.datetime class, not the datetime module:
difference = datetime.datetime.now() - event_date
That said, your correction logic is off. If you write out the calculation in one line, it should be clear why:
difference = datetime.now() - event_date
event_date_new = event_date + difference
So by substitution:
event_date_new = event_date + (datetime.now() - event_date)
Which simplifies to:
event_date_new = datetime.now()
I would try it this way:
now = datetime.datetime.now()
event_date = event_date.replace(year=now.year)
if event_date < now:
event_date.replace(year=now.year + 1)
As Christian Ternus points out, that won't work if event_date is a leap day. You could disallow leap days as event_date values, requiring the user to enter either February 28th or March 1st. Or you could catch the ValueError exception raised by replace and make the correction, adding or subtracting a one-day timedelta. Or use calendar.isleap to figure out the next leap year, if you want to show the true time interval.
datetime is a standard Python module , there's is a object has the same name under this module. now is a class method of the datetime object. So if you want to use datetime.now() you should from datetime import datetime or call datetime.datetime.now()

How do I convert a datetime to date?

How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?
Use the date() method:
datetime.datetime.now().date()
From the documentation:
datetime.datetime.date()
Return date object with same year, month and day.
You use the datetime.datetime.date() method:
datetime.datetime.now().date()
Obviously, the expression above can (and should IMHO :) be written as:
datetime.date.today()
You can convert a datetime object to a date with the date() method of the date time object, as follows:
<datetime_object>.date()
Answer updated to Python 3.7 and more
Here is how you can turn a date-and-time object
(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)
into a date object (aka datetime.date object):
from datetime import datetime
#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)
# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)
# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()
And just to be clear, if you print those elements, here is the output :
print(datetime_element)
2020-07-10 12:56:54.324893
print(date_element)
2020-07-10
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
import time
import datetime
# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
start = end - datetime.timedelta(days=numdays+1)
end = int(time.mktime(end.timetuple()))
start = int(time.mktime(start.timetuple()))
# 86400 s = 1 day
return xrange(start, end, 86400)
# if you need reverse the list of dates
for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):
print datetime.datetime.fromtimestamp(dt).date()
I use data.strftime('%y-%m-%d') with lambda to transfer column to date
Solved: AttributeError: 'Series' object has no attribute 'date'
You can use as below,
df["date"] = pd.to_datetime(df["date"]).dt.date
where in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)
If you are using pandas then this can solve your problem:
Lets say that you have a variable called start_time of type datetime64 in your dataframe then you can get the date part like this:
df.start_time.dt.date

Categories