Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>import datetime as DT import itertools start_date=DT.date(2008,5,5) def mkdate(datestring): return DT.datetime.strptime(datestring, "%Y-%m-%d").date() def fortnight(date): return (date-start_date).days //14 raw = ("2010-08-01", "2010-06-25", "2010-07-01", "2010-07-08") transactions=[(date,"Some data") for date in map(mkdate,raw)] transactions.sort(key=lambda (date,data):date) for key,grp in itertools.groupby(transactions,key=lambda (date,data):fortnight(date)): print(key,list(grp)) </code></pre> <p>yields</p> <pre><code># (55, [(datetime.date(2010, 6, 25), 'Some data')]) # (56, [(datetime.date(2010, 7, 1), 'Some data'), (datetime.date(2010, 7, 8), 'Some data')]) # (58, [(datetime.date(2010, 8, 1), 'Some data')]) </code></pre> <p>Note that 2010-6-25 is in the 55th fortnight from 2008-5-5, while 2010-7-1 is in the 56th. If you want them grouped together, simply change <code>start_date</code> (to something like 2008-5-16).</p> <p>PS. The key tool used above is <code>itertools.groupby</code>, which is explained in detail <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="noreferrer">here</a>.</p> <p>Edit: The <code>lambda</code>s are simply a way to make <a href="http://docs.python.org/reference/expressions.html#lambda" rel="noreferrer">"anonymous" functions</a>. (They are anonymous in the sense that they are not given names like functions defined by <code>def</code>). Anywhere you see a lambda, it is also possible to use a <code>def</code> to create an equivalent function. For example, you could do this:</p> <pre><code>import operator transactions.sort(key=operator.itemgetter(0)) def transaction_fortnight(transaction): date,data=transaction return fortnight(date) for key,grp in itertools.groupby(transactions,key=transaction_fortnight): print(key,list(grp)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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