Why do my dates and times differ? - python

I have in my jinja2 template code for localization.
{% set currency = "SEK" %}
{% set format = "sv_SE" %}
{% set timezoneinfo = 'Europe/Stockholm' %}
{% set locale = "se" %}
But it's not working for hours and minutes if I use it like this with a filter using values from a google search API result to filter.
{{scored_document.fields.10.value|datetimeformat_list(hour=scored_document.fields.17.value|int ,minute =scored_document.fields.18.value|int, timezoneinfo=timezoneinfo, locale=locale)}}
filter
def datetimeformat_list(date, hour, minute, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
input = datetime(date.year, date.month, date.day, int(hour), int(minute), tzinfo=tzinfo)
time_str = format_time(input, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0}".format(time_str)
The code gives a different time than if I just do
{{ ad.modified|datetimeformat_viewad(locale='se', timezoneinfo='Europe/Stockholm') }}
with this filter
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
month = MONTHS[to_format.month - 1]
date_str = '{0} {1}'.format(to_format.day, _(month))
time_str = format_time(to_format, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0} {1}".format(date_str, time_str)
Why are the outputs not the same time?

It is incorrect to pass an arbitrary pytz timezone to datetime constructor directly; you should use pytz_tzinfo.localize() method instead as it is said at the very beginning of pytz docs.
There could be other issues in your code.

Related

How do I convert seconds to hh:mm:ss in django template

So I have a dictionary called match. This has details of a match and one of the keys are game_time. If the game time is <= 10, the match is in draft. Else, I want to report the game time but the value its stored in is just in seconds.
{% if match.game_time <= 10 %}
drafting
{% else %}
{{match.game_time|date: "Z"}}
{% endif %}
Just gives me an error
Could not parse the remainder: ': "Z"' from 'match.game_time|date: "Z"'
any help appreciated
Use this formate for time
{{your_date_field|time:"h:i a"}}
from datetime import datetime, timedelta
def millisec_to_time(millisec):
d = datetime(1, 1, 1)+millisec
if d.day - 1 == 0:
return "{0}:{1}:{2}".format(d.hour, d.minute, d.second)
else:
return "{0}:{1}:{2}:{3}".format(d.day-1, d.hour, d.minute, d.second)
Try this to convert sec/msec to actual time.
If you install mathfilters, add it to your install_apps, and load it into your template then you can do this.
{{ booking.duration|div:3600|floatformat:"2" }}

custom template tag with multiple arguments

I want to format a date in the future based on a time delta:
from django import template
from datetime import datetime, timedelta, time
register = template.Library()
#register.simple_tag
def tomorrow(format):
tommorow = datetime.now() + timedelta(days=1)
return tommorow.strftime(format)
def dayfuture(dday, format):
dayfuture = datetime.now() + timedelta(days=dday)
return dayfuture.strftime(format)
This works:
{% tomorrow "%A, %d %b, %Y" %}
But I've had no luck with dayfuture.
Also, is it possible to have multiple custom template tags in the same file. I've had no luck registering a second one.
I'm using django 1.11 pythone 3.4
This does not work because you did not register it. It is possible to have multiple template tags inside a single file.
def dayfuture(dday, format):
dayfuture = datetime.now() + timedelta(days=dday)
return dayfuture.strftime(format)
You have to put the decorator on it to register it
#register.simple_tag
def dayfuture(dday, format):
dayfuture = datetime.now() + timedelta(days=dday)
return dayfuture.strftime(format)

Converting UNIX time to datetime object in Jinja templates

I want to convert my timestamp to datetime in jinja2..
here's my sample code:
import time
date = time.time()
self.tv['date'] = date
sample html:
<p>{{ date }}</p>
I want to convert it to datetime using jinja2 in python..
thanks..
Make a custom filter like
#app.template_filter('ctime')
def timectime(s):
return time.ctime(s) # datetime.datetime.fromtimestamp(s)
And use your template filter
{{ date | ctime }}
You convert it before passing it to a template, eg:
>>> import time
>>> date = time.time()
>>> from datetime import datetime
>>> datetime.fromtimestamp(date)
datetime.datetime(2013, 3, 1, 2, 57, 29, 472572)
And optionally use formatting:
>>> format(datetime.fromtimestamp(date), '%Y%m%d')
'20130301'
Use this in the template:
{{ time | from_timestamp('%Y.%m.%d. %H:%M:%S UTC') }}
Use the following,
Data
{
"timestamp": "1424197820"
}
Template
{{ timestamp|timestamp_to_time|datetimeformat('%a, %B %d') }}
Rendered
Tue, February 17
Source

Add one day in time from database in django

Hi,
I need to add some condition on the time base , right now the value of time i am getting from database is like 2012-09-05 05:05:05 and i need to add 24 hours in this.
I need to show different content on time base, like for original time i need to show "hi" and after 24 hours i need to show "hello" in the template file.
How can i do this? Please help me.
probably a custom template tag would be a nice way: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters . you could implement your own deltaDays tag with parameters, i.e. {{ date|deltaDays:1 }}.
You could also do this as a cheap filter.
from django import template
register = template.Library()
#register.filter()
def is_at_least_24_hours_ago(value):
import datetime
original_date_plus_24 = value + datetime.timedelta(hours=24)
right_now = datetime.datetime.now()
if right_now >= original_date_plus_24:
return True
return False
Then in your template:
{% if object_date|is_at_least_24_hours_ago %}
// It's 24 hours later
{% else %}
// It's not
{% endif %}
This is sample on how to add day(s),
import datetime
b = var_name + datetime.timedelta(0,3) # days, seconds
or
datetime.timedelta(days=1)
pass the value through view then use if statement in your template

archive list with django templatetags

I have a django application, a blog. The entries for the blog can be accessed through a /year/month/day/slug url pattern, it works fine.
My problem is, I want to have an archive list accessible to any template on my website. So i thought the best solution would be to create a templatetag that would create and return the info i needed.
I wanted the format of the archive to be as such:
August 2011
July 2011
etc..
2010
2009
2008
etc..
So only show months for the current year.
This is the tag i came up with:
from django.template import Library, Node, TemplateSyntaxError
from core.blog.models import Entry
import datetime, calendar
register = Library()
class ArchiveNode(Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
temp = list()
#Get Info about the first post
first = Entry.objects.order_by("pub_date")[0]
first_year = first.pub_date.year
first_month = first.pub_date.month
#Loop over years and months since first post was created
today = datetime.datetime.today()
this_year = today.year
this_month = today.month
for year in range(this_year - first_year):
if year != this_year:
temp += (year,'/blog/'+year+'/')
else:
for month in range(this_month - first_month):
month_name = calendar.month_name[month]
temp += (month_name+" "+year,'/blog/'+year+'/'+month+'/')
context[self.varname] = temp.reverse()
return ''
#register.tag
def get_archive(parser, token):
bits = token.contents.split()
if len(bits) != 3:
raise TemplateSyntaxError, "get_archive tag takes exactly 1 argument"
if bits[1] != 'as':
raise TemplateSyntaxError, "second argument to get_archive tag must be 'as'"
return ArchiveNode(bits[2])
As you can see im returning a list of tuples, containing a name and a url.
Would this be valid in django? or do i need to pack the information in some django container? (It's doen't seem to return anything)
This is the site im working on ctrl-dev.com/blog.
The archive will be in the green box on the lower right.
There is no need to return something special. Django is just Python, so it is your choice what you want to return. In this case I would recommend to return dictionary like this (just inventing) {{'title':'some title if you want','year': 'year if you want', 'url': url}, {...}, ...}. Then in template you just run through like:
{% for entry in returned_dict %}
{{ entry.title }}
{% endfor %}
Also I would recommend to not hardcode the link in to the code. Read https://docs.djangoproject.com/en/dev/topics/http/urls/ about url resolvers, then https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#url about {% url %} template tag. You can name the urls and later you can get the urls to the stuff you want without hardcoding it in the code. This will help in future ;)
Hope that helped.

Categories