7
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ This looks like a bug or at least an developer oversight and insufficient QA checking $\endgroup$ Commented Nov 20, 2015 at 23:45

2 Answers 2

3
$\begingroup$

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"] *) 
$\endgroup$
4
$\begingroup$

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.] *) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.