Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica 8.0 efficient way to parse a DateList from a string in the format of yyyyMMddHHmmssSSS

I have the following string: "20110103224832494" it is in the following format: yyyyMMddHHmmssSSS. Where yyyy is the year, MM is the month, dd is the day, HH is the hour, mm is the minutes, ss is the seconds, SSS is the milliseconds.

I thought that the following would have worked:

DateList[{"20110103224832494",  
         {"Year", "Month", "Day", "Hour", "Minute", "Second", "Millisecond"}}
]

but returns:

DateString::str: String 20110103224832494 cannot be interpreted as a date in 
format {Year,Month,Day,Hour,Minute,Second,Millisecond}. >>

And if that worked, would it have been efficient?

like image 933
mmorris Avatar asked Dec 01 '11 17:12

mmorris


2 Answers

Use:

DateList[{"20110103224832494",  
   Riffle[{"Year",
           "Month", 
           "Day",   
           "Hour", 
           "Minute", 
           "Second", 
           "Millisecond"}, ""]}]
like image 95
Brett Champion Avatar answered Oct 14 '22 23:10

Brett Champion


Corrected to combine milliseconds with seconds.

You did specify "efficient" and I believe this is two orders of magnitude faster than DateList:

stringDynP[s_String, p_] :=
  StringTake[s, Thread@{{0}~Join~Most@# + 1, #} &@Accumulate@p]

toDateList[string_String] := 
  MapAt[#/1000` &, #, -1] &[
    FromDigits /@ stringDynP[string, {4, 2, 2, 2, 2, 5}]
  ]

toDateList["20110103224832494"]
{2011, 1, 3, 22, 48, 32.494}

stringDynP is a string adaptation of my "Dynamic Partition" function.


Warning for Mathematica 7 users: the DateList method produces a spurious result:

{2011, 1, 12, 9, 23, 24.094}

Presumably in version 8 the following method can be used:

DateList[
 {"20110103224832494",
   {"Year", "Month", "Day", "Hour","Minute", "Second", "Millisecond"}},
 DateDelimiters -> None
]
like image 21
Mr.Wizard Avatar answered Oct 14 '22 23:10

Mr.Wizard