I need to find out how many days in between two date ranges. The problem I am having is that I am pulling the dates when I pass the form and they are coming back as unicode objects, therefor this (below) won’t work.
start = data.get('start_date')
mat = data.get('maturity_date')
delta = start - mat
term_string += "%s" % (delta,)
When I try a print statement, the date output is March 01, 2012 because the widget on my form converts it to that format. I am wondering if there is a way to take these unicode strings and convert them back into a date format so I can use delta to get the # of days.
Edit
I am passing the information through print_form() which sends the data from the form to my function that allows me to fill a pdf with the information.
print_form from lib/tools.py
def print_form(client=None, data=None, investment_form=None, type="gic_application", plan=None, investment=None):
...
if data:
term_string = ''
total_days = 0
if investment:
if investment.term_years:
term_string += "%s" % (investment.term_years,)
fdf += fdf_val_str("term_years", investment.term_years)
fdf += fdf_val_str("Term", "Years")
if investment.term_months:
start = data.get('start_date')
mat = data.get('maturity_date')
delta = start - mat
term_string += "%s" % (delta,)
fdf += fdf_val_str("Term", "Days")
if investment.term_days:
total_days += investment.term_days
term_string += "%s" % (total_days,)
fdf += fdf_val_str("Term", "Days")
...
response = HttpResponse(fdf.encode("ISO-8859-1"), mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=form.xfdf'#% download_filename# % (statement_date, "statements")
return response
And these are the date fields from my forms.py
start_date = forms.DateField(widget=DateInput, required=False)
maturity_date = forms.DateField(widget=DateInput, required=False)
See Alasdair’s comment above; however, for the sake of completion:
Even if you are not using django’s form processing, let’s say the data were coming in from a text file, or something like that and you just want to parse the data directly without using the Form api, you can always convert datetime strings in python by using the tools in the datetime module, these are: strftime and strptime. The notation for conversion is fairly standard across several language implementations.
I worked on something not too long ago where the text file was extremelly large, but all the data was predictable and guaranteed to be error free. To insert into postgres would have added a significant amount of time using the form’s api, so I was parsing directly using python, and saved several hours (these were very complex inserts and several million line items)
Regarding strftime and strptime, the docs are found here: http://docs.python.org/library/datetime.html#strftime-strptime-behavior
All that said, I think Alasdair’s comment will fix your specific problem.