Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Interesting question, and here's a complete solution. I'll start with my function definition, I've put this in a file named <code>payday.py</code>:</p> <pre><code>def nexypayday(fromdate=None): """ @param fromdate: An instance of datetime.date that is the day to go from. If not specified, todays date is used. @return: The first payday on or after the date specified. """ </code></pre> <p>Next we need some tests. This is to clearly define the behaviour of our method. Because you're new to python, I'm going to go all out and give you an example of using unittests.</p> <pre><code>from unittest import TestCase, main import payday import datetime class TestPayday(TestCase): def test_first_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 1)), datetime.date(2010, 1, 1)) def test_second_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 2)), datetime.date(2010, 1, 15)) def test_fifteenth_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 15)), datetime.date(2010, 1, 15)) def test_thirty_one_jan(self): self.assertEqual(payday.nextpayday(datetime.date(2010, 1, 31)), datetime.date(2010, 2, 1)) def test_today(self): self.assertTrue(payday.nextpayday() &gt;= datetime.date.today()) if __name__ == '__main__': main() </code></pre> <p>This is a runnable python module. You can go ahead and name that <code>test_payday.py</code> and run it with <code>python test_payday.py</code>. This should immediately fail with various error messages because we've not got the right code written yet.</p> <p>After some fiddling with how datetime.date works, I've worked out: <code>mydatetime.day</code> is the day of the month, <code>mydatetime + datetime.timedelta(days=1)</code> will create a new <code>datetime</code> one day on in the year. Thus I can throw together this in <code>payday.py</code>.</p> <pre><code>import datetime def nextpayday(fromdate=None): """ @param fromdate: An instance of datetime.date that is the day to go from. If not specified, todays date is used. @return: The first payday on or after the date specified. """ if fromdate is None: fromdate = datetime.date.today() # while the day of the month isn't 1 or 15, increase the day by 1 while fromdate.day not in (1, 15): fromdate = fromdate + datetime.timedelta(days=1) return fromdate </code></pre> <p>Run the unit tests and it should be all golden. Note that in my tests I've made it that if I check what the 'next' payday is from a payday, it returns its own day. Changing that to returning the 'next' payday is left as an exercise for the reader. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload