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.
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.
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.
today = datetime.now()
{% if x.for_meeting.date_created.date < today.date and x.for_meeting.date_created.time < today.time %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With