1

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).

asked Nov 17, 2014 at 21:53
1
  • 1
    Where does that Date class come from? Why are you not using datetime.date? Commented Nov 17, 2014 at 21:56

2 Answers 2

2

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
answered Nov 17, 2014 at 21:57
Sign up to request clarification or add additional context in comments.

1 Comment

Date calculation is hard. Why reinvent the wheel? Or are you just doing this as a learning experience?
0

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)

answered Nov 17, 2014 at 21:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.