Issue
I'm trying to display the difference between 2 giving dates on django, and i've managed to make it, but now i'm strugling to display only the days, without the time, is there any filter that i can use?
My html template:
<a href="{% url 'edit_contract' contract.id %}">
{% if contract.status == 'PN' %}
{{ today |sub:contract.starting_date }}
{% else %}
TODO
{% endif %}
</a>
My view:
@login_required
def contract_list(request):
contracts = Contract.objects.filter(user=request.user)
total_contracts_value = Contract.objects.filter(user=request.user).aggregate(sum=Sum('value'))['sum'] or 0
contracts_count = Contract.objects.filter(user=request.user).count()
today = date.today()
return render(request, 'list_contract.html', {'contracts': contracts,
'total_contracts_value': total_contracts_value,
'contracts_count': contracts_count, 'today':today})
Solution
I think there are a few ways to do what you want here. I'll let you decide what you think works best for you.
- The
timesince
ortimeuntil
template formatting tags within Django may give you what you want immediately.
{{ today |timeuntil:contract.starting_date }}
https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#timesince https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#timeuntil
- Another option is to make use of the
datetime
module.
Here us an example showing the difference in days between a datetime object:
import datetime
now = datetime.datetime.now()
startingDate = now + datetime.timedelta(days=7)
daysRemaining = (startingDate-now).days
print(daysRemaining) # INFO: prints '7'
I don't think this is what you want, but here is another example, using strftime
and timedelta
to get more specific formatting:
todaysDateFormatted = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=1), "%d-%b-%Y")
Answered By - FlippinBits
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.