George Washingpound
George Washingpound

Reputation: 25

Python Calculation

I'm trying to write a method different(self, other) that returns an integer that represents the # of days between self(one calendar date) and other(another calendar date).

Upvotes: 1

Views: 80

Answers (2)

thebjorn
thebjorn

Reputation: 27311

Convert to datetime.date

def diff(a, b):
    adate = datetime.date(a.year, a.month, a.day)
    bdate = datetime.date(b.year, b.month, b.day)
    return abs(adate.toordinal() - bdate.toordinal())

you can get this for free in your Date class if you inherit from `datetime.date (check out the ttcal module I wrote for a time-tracking app for an example: https://github.com/datakortet/dk/blob/master/dk/ttcal.py#L471)

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336088

You haven't shared your Date class with us, but Python already provides one, complete with methods to calculate date differences:

>>> from datetime import date
>>> a = date(2014,11,10)
>>> b = date(2014,12,24)
>>> b-a
datetime.timedelta(44)
>>> (b-a).days   # if you need the number of days as an integer
44

I usually prefer datetime.datetime, though - it provides greater accuracy and more methods to manipulate dates:

>>> from datetime import datetime
>>> a = datetime(2014,11,10)  # works just the same, but you can also
>>> b = datetime(2014,12,24)  # add hours/minutes/seconds etc.
>>> b-a
datetime.timedelta(44)
>>> (b-a).days
44

Upvotes: 2

Related Questions