Search code examples
rdatetimetimestampnumeric

How to convert numeric numbers to time stamp using R


I used this script

 df?timestamp< as.POSIXct(df$timestamp,tz="",format="%Y%m%d%H%M%S",origin = "1970-01-01")

then i get NA's.

The number i have is 43466.10 and the result i should get is 2019-01-01 02:17:26.

What am i supposed to do?


Solution

  • In fact, 43466.10 is not a valid Unix epoch time. See https://en.wikipedia.org/wiki/Unix_time for more information.

    This number looks like an Excel date/time value. If that truly is, then "2019-01-01 02:17:26" is actually 43466.0954398148, and the origin you should use is "1899-12-30", not "1970-01-01".

    You cannot use as.POSIXct directly in this case because UNIX epoch time is in counting seconds, but an Excel date/time value is in counting days.

    You can use the package openxlsx to do this conversion. Try this:

    # install.packages("openxlsx")
    df$timestamp <- openxlsx::convertToDateTime(df$timestamp, origin = "1899-12-30")