8

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.

Randy Howard
  • 2,165
  • 16
  • 26
masterofdestiny
  • 2,751
  • 11
  • 28
  • 40

4 Answers4

12
today =  datetime.now()

{% if x.for_meeting.date_created.date < today.date and x.for_meeting.date_created.time < today.time  %}
catherine
  • 22,492
  • 12
  • 61
  • 85
6

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.

Janne
  • 105
  • 1
  • 5
5
{% if date_created|date:"YmdHis" < now|date:"YmdHis" %}

{% endif %}
iHTCboy
  • 2,715
  • 21
  • 20
0

To compare object.created_at == TODAY

{% now "Ymd" as today_str %}
{% if object.created_at|date:"Ymd" == today_str %}
True
{% endif %}
C.K.
  • 4,348
  • 29
  • 43