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

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" }}

Related

Passing list dict to template not working django

I am trying to pass a list called eligable so that I can display on my website but when I run my website it does not display the list. I do not understand what is wrong.
code:
def specificDate(response):
empName = employeeName.objects.all()
eligable = []
if 'checkEmployee' in response.POST:
n = response.POST.get("nameEmployee")
specDate = response.POST.get("date")
if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists():
emp = employeeName.objects.get(employee=n)
t = Name.objects.get(name=emp, date=specDate)
overT = Name.objects.filter(name=emp, overtime=True)
for item in overT:
eligable.append(item.date)
checkIn = t.timeIn.strftime("%H:%M:%S")
checkOut = t.timeOut.strftime("%H:%M:%S")
datee = datetime.strptime(specDate,'%Y-%m-%d')
print("Here:: ",t.date)
print("Month:: ",datee.month)
messages.info(response, checkIn + ' - ' + checkOut)
return redirect('/specificDate')
else:
messages.info(response, 'Name does not exist')
else:
pass
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
This is the html to print my list:
{% for item in eligable %}
<div class="pad3">
{{item}}
</div>
{% endfor %}
There are two return statements in your code:
return redirect('/specificDate')
and
return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable})
The first one is just redirecting without populating context.
The second one does populate context but is reached only when eligable is empty.
I think changing the first return to the second one should solve it.
edit: and you are missing {% endfor %} here. But it should give you an error if you miss it in your complete code.

Python Flask output dropdown values to page

I have a two dictionaries with several keys and one value for each key. One dict has weekly cumulative work hours, the other weekly cumulative overtime hours. The key is a datetime object, which is calculated to be the beginning of a week. On my webpage I have a dropdown box, which contains the week beginnings
<form action="{{ url_for('index') }}" method="post">
<select class="form-control" name="cumuls" id="select1" onchange="if(this.value != 0) { this.form.submit(); }">
<option value="0">Cumulative for week beginning...</option>
{% for i,j in zip(wks, wks2) %}
<option value="{{ i }}">{{ j }}</option>
{% endfor %}
</select>
</form>
(wks2 is just a nicely formatted version of wks, and wks is just a list of the keys from the dicts which are datetime objects (the dictionaries have the same keys))
I want to be able to click on an option from the dropdown box and for the corresponding values from the two dictionaries to appear below the dropdown box.
I handle the form here (within an index() function), after the if is the end of the index function:
if request.method == 'POST':
if 'cumuls' in request.form:
week_Begin = request.form['cumuls']
listHours = listDates(current_user.get_id())
dct_hours, dct_overtime, wks = weeklySum2(listHours)
#strfdelta is a custom function that formats timedeltas
cumul_hrs = strfdelta(dct_hours[datetime.fromisoformat(week_Begin)], '%H:%M')
cumul_overtime = strfdelta(dct_overtime[datetime.fromisoformat(week_Begin)], '%H:%M')
return redirect(url_for('index'))
listHours = listDates(current_user.get_id())
dct_hours, dct_overtime, wks = weeklySum2(listHours)
print(wks)
# wkbgn = weekbeginning, this just formats the dates nicely
wks2 = [wkbgn.strftime('%A') + ' ' + wkbgn.strftime('%-d') + ' ' + wkbgn.strftime('%b') + ' ' + wkbgn.strftime('%Y') for wkbgn in wks]
currentDay = datetime.today()
start_week = (currentDay - timedelta(days=currentDay.weekday()))
return render_template('index.html', form=form, hoursDb = listHours, dct_overtime=dct_overtime,dct_hours=dct_hours, wks=wks, wks2=wks2, zip=zip)
So within the if 'cumuls'..., I basically get the cumulative working and overtime hours for the selected week, in cumul_hrs and cumul_overtime, which works. I essentially want these variables to be displayed on the webpage (below the dropdown box), and the default variable that is displayed will be the current weeks cumulative so far. How could I do this?
Any pointers/tips are greatly appreciated.
I ended up just changing the redirect within the elif statement to
return redirect(url_for('index', cumul_hrs=cumul_hrs, cumul_overtime=cumul_overtime))
and then getting the variables from the URL with:
cumul_hrs, cumul_overtime = request.args.get('cumul_hrs'), request.args.get('cumul_overtime')
and passing them through render_template.

Why do my dates and times differ?

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.

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