I have two methods that I'm using as custom tags in a template engine:
# Renders a <select> form field
def select_field(options, selected_item, field_name):
options = [(str(v),str(v)) for v in options]
html = ['<select name="%s">' % field_name]
for k,v in options:
tmp = '<option '
if k == selected_item:
tmp += 'selected '
tmp += 'value="%s">%s</option>' % (k,v)
html.append(tmp)
html.append('</select>')
return '\n'.join(html)
# Renders a collection of <select> fields for datetime values
def datetime_field(current_dt, field_name):
if current_dt == None:
current_dt = datetime.datetime.now()
day = select_field(range(1, 32), current_dt.day, field_name + "_day")
month = select_field(range(1, 13), current_dt.month, field_name + "_month")
year = select_field(range(datetime.datetime.now().year, datetime.datetime.now().year + 10), current_dt.year, field_name + "_year")
hour = select_field(range(1, 13), current_dt.hour, field_name + "_hour")
minute = select_field(range(1, 60), current_dt.minute, field_name + "_minute")
period = select_field(['AM', 'PM'], 'AM', field_name + "_period")
return "\n".join([day, '/', month, '/', year, ' at ', hour, ':', minute, period])
As you can see in the comments, I'm attempting to generate select fields for building a date and time value.
My first question is, how do I make the day, month, hour, and minute ranges use two digits? For example, the code generates "1, 2, 3..." while I would like "01, 02, 03".
Next, when the fields get generated, the values of the supplied datetime are not selected automatically, even though I'm telling the select_field method to add a "selected" attribute when the value is equal to the supplied datetime's value.
Finally, how do I get the 12-hour period identifier (AM/PM) for the supplied datetime? For the moment, I'm simply selecting 'AM' by default, but I would like to supply this value from the datetime itself.