[Tutor] date range

Ben Finney ben+python at benfinney.id.au
Tue Feb 2 20:37:52 EST 2016


Chelsea G <cegarcia0323 at gmail.com> writes:

> So I am taking in a csv file with several rows and one of those rows
> in a date row.

That doesn't make much sense, as a sepcification. CSV is by design a
data format in which every data row has the same structure: the fields
always have the same meaning, in the same order.

> I am trying to see if I can read in a csv file and search for a
> certain date range like 1/2/2016 to 1/5/2016.

You can, by breaking the problem into simpler problems:

* Get the rows into some collection of structured records. (The
  Python standard library's ‘csv.DictReader’ is your friend here.)

* Identify which field of the record is the data on which you want to
  filter. (For a collection of records you retrieved from reading a
  ‘csv.DictReader’, you need to know which field name has the dates
  you're interested in.)

* Construct an expression that takes an arbitrary date value as found in
  that field, and interrogates it by some comparison that evaluates to
  True when the value is in your specified range and False otherwise.

* Construct a new collection of records, by iterating the full
  collection and only accumulating the ones which match your criteria.

Each of those is much simpler that the original problem. Solve each of
them separately, and it should then be much easier to put the solutions
together to solve the larger problem.

-- 
 \          “Friendship is born at that moment when one person says to |
  `\    another, ‘What! You too? I thought I was the only one!’” —C.S. |
_o__)                                                            Lewis |
Ben Finney



More information about the Tutor mailing list