Calculate number of days between two dates inside Django templates - python

I have two dates and want to show a message like "n days left before your trial end." where n is a number of days between two given dates. Is that better to do this inside views or is there a quick way to do it inside template itself?

Use timesince template tag.

This code for HTML in Django. You can easily find the remaining days.
{{ to_date|timeuntil:from_date }}
Otherwise, you can use custom TemplateTags.

Possible duplicate here
I'd actually use the same method lazerscience uses, something like this:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince
register = template.Library()
#register.filter
def time_until(value):
now = datetime.now()
try:
difference = value - now
except:
return value
if difference <= timedelta(minutes=1):
return 'just now'
return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}

In the HTML template, you can do the following:
{{ comments.created|timeuntil:project.created }}
And you get output something like this:
1 hour, 5 minutes

Related

Hiding milliseconds from timezone.now() (In HTML)

I am building a BlogApp and I am implementing a feature of expiring post so the post will hide in 2 days, So I am showing user the remaining time in post.
Remaining time is showing perfectly BUT It is also showing milliseconds (which i I am trying to hide)
The Output is like :-
2 days, 23:43:33.271449
views.py
from django.utils import timezone
from datetime import timedelta
def blogpost_detail(request,blogpost_id):
blog = get_objects_or_404(BlogPost,pk=blogpost_id)
remaining_time = blog.blog_date_added - timezone.now() + timedelta(days=2)
context = {'remaining_time':remaining_time,'blog':blog}
return render(request, 'blogpost_detail.html', context}
What i am trying to show as output :-
I am trying to show like :-
2 days 23 Hours Remaining
What have i tried :-
I tried Python/Django timestamp including milliseconds Post's Answer by dividing 1000 but when i divide timezone by 1000 like timezone.now()/1000 then it is keep showing
unsupported operand type(s) for /: 'datetime.datetime' and 'int'
Then i tried hiding milliseconds from template by using time:"h:i a" like {{ blog.blog_date_added|time:"h:i a" }}
But it is showing nothing as output.
When i try to add naturaltime like {{ blog.blog_date_added|naturaltime }} then it is showing the same output.
When i try to add timesince like {{ blog.blog_date_added|timesince }} then it is showing :-
'datetime.timedelta' object has no attribute 'year'
Any help would be much Appreciated. Thank You in Advance
I would advise that you add a property to your Blog when the blog will expire, something as:
from datetime import timedelta
class Blog(models.Model):
# &vellip;
#property
def expire_date(self):
return self.blog_date_added + timedelta(days=2)
In the template we can then work with the |naturaltime template filter:
{% load humanize %}
{{ blog.expire_date|naturaltime }}

Time limit in django template

I need a help with time-limit. I want to show user how many time he has got to rent a car.
This is my views:
class CarRentView(RedirectView):
permanent = False
query_string = True
model = Car
def date_of_return(request):
car = Car.objects.all()
car.rent = True
date_of_rent = datetime.now()
date_of_rent = car.save()
car_return_date = date_of_rent+timedelta(days=30)
return render(request, 'cars','car_return_date')
and when I want to do this in my template:
{{ car_return_date }}
there is nothing and I don't know, what's wrong. Is there any possibility to show return date and after this make a count?
You need to call the render function differently:
return render(request, 'myapp/index.html', {'cars': car, 'car_return_date': car_return_date})
See the docs for more information.
Besides, I don't think you are setting the car.rent correctly, since you are setting it on all cars.
Variables that you return to your template need to be returned as part of a context dictionary. So you would have:
return render(request, 'my_template.html', {'car': car, 'car_return_date': car_return_date})
The car_return_date variable will then be available in your template using:
{{ car_return_date }}
You will also probably want to use the date filter when outputting the datetime object. For example, you could use:
{{ car_return_date|date:"j N Y" }}
I would suggest changing date_of_rent to last_date_of_rent by adding 30 days to it. And then, saving last_date_of_rent to the models. So you can use, last_date_of_rent directly in the templates. Further the use of in-built template filter timeuntil will return the desired. -
{{ car.last_date_of_rent|timeuntil }}
Documentation:
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#timeuntil

Generating a date relative to another date in Django template

I have a date in my template context, and I want to display that date plus 7 days in the rendered output.
Something like this (which does not exist):
{{some_date|plus_days:7}}
How can I do this in a Django template without writing any Python code?
You can create your own template tag:
import datetime
from django import template
register = template.Library()
#register.filter
def plus_days(value, days):
return value + datetime.timedelta(days=days)
This cannot be done in Django templates as of this writing without writing a custom template tag in Python.

print page generation time

how would I print the time it took to render a page to the bottom of my site in django? i'm not sure of the application flow of django, so I don't know how this would work.
You might be interested in django-debug-toolbar, which includes a request timer and lots of other useful info for debugging things like this.
At the beginning of your view handler, save the current date/time in a variable say time_start and pass that to the template context which renders the page.
Then define a custom template filter that will create timedelta based on datetime.now() value and the original datetime passed in as a parameter like so:
from datetime import datetime
from django import template
register = template.Library()
#register.filter
def get_elapsed(time_start):
return str(datetime.now() - time_start)
Then in your template, simply display:
...
{{ time_start|get_elapsed }}
...

How do I display current time using Python + Django?

I am learning how to use Python and Django to produce a small webapp that prints out the current time. I am using this with the Google App Engine.
Right now it's only displaying a blank page, but I want it to display the current time. I also want to map the function to the home page.. not /time/.
from django.http import HttpResponse
from django.conf.urls.defaults import *
import datetime
# returns current time in html
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
def main():
# maps url to current_datetime func
urlpatterns = patterns('',
(r'^time/$', current_datetime),
)
if __name__ == '__main__':
main()
Maybe this documentation is useful to you: Time Zones
Formatting time in a view
You can get the current time using:
import datetime
now = datetime.datetime.now()
or
to get time depending on timezone:
import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
to format the time you can do:
import datetime
now = datetime.datetime.now().strftime('%H:%M:%S') # Time like '23:12:05'
Formatting time in a template
You can send a datetime to the template, let's supose you send a variable called myDate to the template from the view. You could do like this to format this datetime:
{{ myDate | date:"D d M Y"}} # Format Wed 09 Jan 2008
{{ myDate | date:"SHORT_DATE_FORMAT"}} # Format 09/01/2008
{{ myDate | date:"d/m/Y"}} # Format 09/01/2008
Check the Template filter date
I hope this is useful to you
Use the now template tag. For example:
{% now "jS F Y H:i" %}
but you'll need to send your string through template engine before sending the response for it to work.
For Django code, not in template the support is actually quite simple.
In settings change the timezone:
TIME_ZONE = 'Asia/Kolkata'
And where you need to use, use the following code:
from django.utils import timezone
now = timezone.now()
Source: https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/
You can use time.strftime() for printing the current time. In your urlpatterns, just change '^time/$' to '^/$' to map the root page to your time function.

Categories