How do I obtain the delta between two dates?

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

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

The dateutil module is really nice for parsing dates:

>>> from dateutil.parser import parse
>>> parse("05/01/2012") - parse("04/01/2012")

Need Your Help

Already Registered at /admin/ Django 1.2 error

django django-admin

I'm experiencing this error in Django 1.2 admin.

SetupVerifyInfFile returns ERROR_INVALID_PARAMETER (0x57) for windows xp

c++ setupapi

This code successfully works on Vista/Win7, but it fails on win xp (returns ERROR_INVALID_PARAMETER). There're no docs in internet about this problem. Does anybody know where the mistake is? Thanks.