I've been searching around before asking this.
I have Django template, which inputs a water account number, a beginning date, and an ending date. The dates define a search range, and are in mm/dd/yyyy format.
I'd like to convert these dates into a Python format, so I can find the difference between them. I'm aware of date and datetime objects, and I know I can parse -- for example -- 05/01/2012 -- and create a date object from that.
However, I'm interested in a better way to this, like converting the "05/01/2012" directly for start and end date range values, and then taking the delta between those Python date objects.
Thank you.
Edit: This is what I'm using to calculate the delta:
d1 and d2 are date strings in the form: mm/dd/yyyy.
def time_delta(d1, d2):
dd1 = datetime.strptime(d1, "%m/%d/%Y").date()
dd2 = datetime.strptime(d2, "%m/%d/%Y").date()
delta = dd2 - dd1
return delta.days
Maybe something like this?
from datetime import *
d1 = datetime.strptime('05/01/2012', "%d/%m/%Y").date()
d2 = datetime.strptime('06/01/2012', "%d/%m/%Y").date()
delta = d2 - d1
print(delta.days)
You should be using Django forms for this kind of thing. If you use date fields, then start_date
and end_date
will be Python date objects when you you fetch them out of the form's cleaned data dictionary.
If you haven't used Django forms before, then I recommend that you read through the forms documentation. Here's a couple of snippets as a hint.
class MyForm(forms.Form):
start_date = forms.DateField()
end_date = forms.DateField()
# other fields e.g. water account number
# in your view
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
delta = end_date - start_date
# do anything else you need to do
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With