7

I have a date/time string from a data file in the form "2014/01/09 07:24:36:001".

I would like to convert it to a DateObject. I cannot do it by hand because I have about a thousand of them.

This does not work:

DateObject["2014/01/09 07:24:36:001", 
 DateFormat -> {"Year", "/", "Month", "/", "Day", " ", "Hour24", ":", 
   "Minute", ":", "Second", ":", "Millisecond"}]

It returns the error:

DateObject::str: String 2014/01/09 07:24:36:001 cannot be interpreted as a date.

This does work however so I think DateObject does not like the "Millisecond" part.

DateObject["2014/01/09 07:24:36", 
 DateFormat -> {"Year", "/", "Month", "/", "Day", " ", "Hour24", ":", 
   "Minute", ":", "Second"}]

How do I convert the date/time string "2014/01/09 07:24:36:001" to a DateObject without losing the fractional second information?

MarcoB
  • 67,153
  • 18
  • 91
  • 189
Rudy
  • 125
  • 6

2 Answers2

4

Using DateList first and then using DateObject seems to work:

DateObject[
 DateList[{"2014/01/09 07:24:36:985", {"Year", "/", "Month", "/", 
    "Day", " ", "Hour24", ":", "Minute", ":", "Second", ":", 
    "Millisecond"}}]]

The fractional seconds are in the DateObject, but are not displayed.

Consider:

date1 = DateObject[DateList[{"2014/01/09 07:24:36:555", {"Year", "/", "Month", "/","Day", " ", "Hour24", ":", "Minute", ":", "Second", ":","Millisecond"}}]]
date2 = DateObject[DateList[{"2014/01/09 07:24:36:100", {"Year", "/", "Month", "/","Day", " ", "Hour24", ":", "Minute", ":", "Second", ":", 
 "Millisecond"}}]]
FullForm[date1]
FullForm[date1 - date2]

This is directly visible by looking at the InputForm, e.g.

InputForm@date1
(* 
 DateObject[{2014, 1, 9}, TimeObject[{7, 24, 36.555}, TimeZone -> -6.], TimeZone -> -6.]
*)
rcollyer
  • 33,976
  • 7
  • 92
  • 191
Rudy
  • 125
  • 6
3

Here is a helper function to interpret your dates:

Clear[interpretDate]

interpretDate[string_String] :=
 Module[
   {year, month, day, hours, minutes, seconds, milliseconds},
   {year, month, day, hours, minutes, seconds, milliseconds} =
    ToExpression@StringSplit[string, {":", "/", " "}];
  DateObject[
   {year, month, day},
   TimeObject[{hours, minutes, seconds}] + Quantity[milliseconds, "ms"]
  ]
 ]

See for instance:

firstdate = interpretDate["2014/01/09 07:24:36:001"];
seconddate = interpretDate["2014/01/09 07:24:36:450"];
seconddate - firstdate

(* Out: Quantity[0.4489998817443847, "Seconds"] *)
MarcoB
  • 67,153
  • 18
  • 91
  • 189