3

I have some objects whicha re associated with dates. I would like to be able to get objects for a given date range, as well as for a single date. What is the best data structure in python to do this?

I believe in some languages this would be achieved using a 'Curve'.

user1742188
  • 4,563
  • 8
  • 35
  • 60
  • I think you are looking for the Python-equivalent of a Java [TreeMap](http://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html). Something like [this](http://stackoverflow.com/q/6886294/1639625)? – tobias_k Jul 15 '16 at 22:15

2 Answers2

3

You could use a pandas DataFrame:

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.random((10,1)))
df['date'] = pd.date_range('2016-7-1', periods=10, freq='D')

For a date range:

>>> df[(df['date'] > '2016-7-3') & (df['date'] <= '2016-7-10')]
          0       date
3  0.322654 2016-07-04
4  0.360684 2016-07-05
5  0.298821 2016-07-06
6  0.292097 2016-07-07
7  0.052085 2016-07-08
8  0.620535 2016-07-09
9  0.902022 2016-07-10

For a given date:

>>> df[df['date'] == '2016-7-3']
          0       date
2  0.191553 2016-07-03
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
1

A dictionary would work. datetime objects can be used as dictionary keys, and can be compared against one another in ranges.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • But this does not work if the date you want to look up is between two dates in the dict. – tobias_k Jul 15 '16 at 22:14
  • I assumed the poster was asking for 'tell me if stored date X is between arbitrary dates Y and Z, not 'tell me if arbitrary date X is between stored dates Y and Z'. But even then it would work, you'd just need to compare each unique pair of dates in the dict against the target date. – John Gordon Jul 15 '16 at 22:21