Mathematica, an efficient way to compare dates

I have a list like this:

{{2002, 4, 10}, 9.61}, {{2002, 4, 11}, 9.53}, {{2002, 4, 12}, 9.58},


I need to find this list to find the exact date match, if there is no match I will have the next available date in the list, here is my code:

Select[history, DateDifference[#[[1]], {2012, 3, 17}] <= 0 &, 1]


but this is much slower than just finding an exact match, is there a faster way to do this? Thank you very much!


source to share

4 answers

finddate[data:{{{_Integer, _Integer, _Integer}, _}..}, 
   date:{_Integer, _Integer, _Integer}] := 
  First[Extract[data, (Position[#1, First[Nearest[#1, AbsoluteTime[date]]]] & )[
     AbsoluteTime/@ data[[All,1]]]]]


will do what you want. For example.

finddate[{{{2002, 4, 10}, 9.61}, {{2002, 4, 11}, 9.53}, {{2002, 4, 12}, 9.58}}, 
{2012, 3, 17}]


gives {{2002, 4, 12}, 9.58}

It seems to be fast enough (half a second for 10 ^ 5 dates).



It is true that it is DateDifference

quite slow. This can be worked around by converting all dates to "absolute times", which in Mathematica means the number of seconds since 1900 on January 1.

Here's an example. This is the data:

data = {AbsoluteTime[#1], #2} & @@@ 
   FinancialData["GOOG", {{2010, 1, 1}, {2011, 1, 1}}];


We are looking for this date or the next one if it is not available:

date = AbsoluteTime[{2010, 8, 1}]


One way to get it:

dt[[1 + LengthWhile[dt[[All, 1]], # < date &]]]


You will find other methods in the answers to this question, including the already implemented binary search .



Could you / would you be quicker to write a binary search assuming your story is ordered?

This should give you a date in the log (n) comparison which is better than the line filter you are currently using. If you provide a date, if it exists, or if the date does not exist, it will give you where you should insert the new date.



The fastest thing for many accesses to the same dataset is to create an interpolation function based on the AbsoluteTime [] of the date and value. If the default is changed incorrectly, you can undo all the "seconds" and it will wobble that way.



All Articles