Search code examples
datetimef#deedle

calculate timespan from two frame columns


I have a deedle frame with two columns containing DateTime timestamps. I would like to calculate the difference (timaspan) between the two

type Test = { 
    id : int;
    start : DateTime;
    finish : DateTime    }

let testData = [
    {id = 1; start = DateTime.Parse("13.01.2014 00:45:38"); finish = DateTime.Parse("13.01.2014 03:15:39")};
    {id = 2; start = DateTime.Parse("15.01.2014 00:30:38"); finish = DateTime.Parse("16.01.2014 01:07:39")}]

let testFrame = Frame.ofRecords testData

testFrame?TimeSpan <- testFrame |> Frame.mapRowValues (fun row -> 
    row?finish - row?start )

Solution

  • The use of the ? operator in row?finish is a shortcut for row.GetAs<float>("finish") meaning that it accesses a column and attempts to convert it to float - the operator does this simply because this seems to be the most common case and so we wanted to make it simple.

    If you need to work with other types, then you need to use GetAs explicitly:

    testFrame?TimeSpan <- testFrame |> Frame.mapRowValues (fun row -> 
        row.GetAs<DateTime>("finish") - row.GetAs<DateTime>("start") )
    

    Also check this MSDN documentation page which discusses the difference between using DateTime and DateTimeOffset to make sure you're using the right type for representing times.