Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime compare in django template

Tags:

django

I am having a problem while comparing two dates in Django templates.

I have a date field in my model:

 date_created = models.DateTimeField(auto_now=True)

I want to compare date_created by today date. So this is what I am doing in my django template:

{% if x.for_meeting.date_created < today%} # (x is the instance of MeetingRecord class where for_meeting field is Foreign key to Meeting table Where date_created)

Now I am calculating today in view like:

today =  datetime.now().strftime("%B %d, %Y,%I:%M %P")

Unfortunately I am not able to compare the dates.

Please tell me what might I am doing wrong here.

like image 820
masterofdestiny Avatar asked Mar 28 '13 06:03

masterofdestiny


People also ask

How do you compare DateTime dates?

The DateTime. Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value, <0 − If date1 is earlier than date2.

What are templates in Django?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


2 Answers

today =  datetime.now()

{% if x.for_meeting.date_created.date < today.date and x.for_meeting.date_created.time < today.time  %}
like image 54
catherine Avatar answered Oct 14 '22 11:10

catherine


You don't have to create the today variable (in a view), just use the {% now %} template tag already available.

And, when comparing DateTimeField objects in Django templates, make sure to compare them in the same timezones. You might want to make this explicit, for clarity and compatibility with timezone changes:

{% load tz %}

{% if date_created|utc < now|utc %}

This evaluates to False, if dead_deadline is None or => than the current datetime.

By default (for me), the date_created is in database time (UTC) and now is in localtime as set in settings.py.

Ensure also, the values you compare, have meaningful values.

PS. If you try to use the localtime filter to convert a datetime object formated to "Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC)" i.e. date:"U", the output will None.

like image 45
Janne Avatar answered Oct 14 '22 12:10

Janne