Search code examples
rdatenetcdfposixct

Convert from minutes since origin to date time for normal people ("yyyy-mm-dd HH:MM:SS")?


I'm working with a netcdf file which has its time units described as: "minutes since 1850-01-16T14:06:00"

I'd like to have it in a more familiar date format for easier date matching and processing. The origin is given which is helpful, but I can't determine if I am using the wrong parsing formats or if the dates truly are not in line with the expectations I had.

I checked the help for strptime() and as.POSIXct() and haven't been able to figure out what format to use to parse this bizarre time structure.

# Example of the origin format and first 8 values
origin <- "1850-01-16T14:06:00"
dates_as_times <- c(52559874, 52602354, 52644834, 52688754, 
                    52732674, 52776594, 52820514, 52865154)

Solution

  • There are some packages for converting the netcdf files

    library(RNetCDF)
    library(lubridate)
    out <- utcal.nc("minutes since 1850-01-16T14:06:00", dates_as_times)
    out
    #     year month day hour minute second
    #[1,] 1949    12  23   12      0      0
    #[2,] 1950     1  22    0      0      0
    #[3,] 1950     2  20   12      0      0
    #[4,] 1950     3  23    0      0      0
    #[5,] 1950     4  22   12      0      0
    #[6,] 1950     5  23    0      0      0
    #[7,] 1950     6  22   12      0      0
    #[8,] 1950     7  23   12      0      0
    

    From the matrix, it can be easily converted to Datetime object with ISOdatetime

    with(as.data.frame(out), ISOdatetime(year, month, day,
            hour, minute, second, tz = 'GMT'))
    #[1] "1949-12-23 12:00:00 GMT" "1950-01-22 00:00:00 GMT" "1950-02-20 12:00:00 GMT" "1950-03-23 00:00:00 GMT"
    #[5] "1950-04-22 12:00:00 GMT" "1950-05-23 00:00:00 GMT" "1950-06-22 12:00:00 GMT" "1950-07-23 12:00:00 GMT"
    

    Or another option is

    library(ncdf.tools)
    convertDateNcdf2R(dates_as_times, origin = ymd_hms(origin))
    

    Or we could multiply with 60

    as_datetime(dates_as_times * 60, origin = ymd_hms(origin))