Home > Blockchain >  Converting numbers into time and date
Converting numbers into time and date

Time:12-13

I am trying to convert numeric values into times and dates. I am working with a data set so it would be appreciated if you should show an example using a dataset.

Here are some examples, converting 93537 into 09:35:57 (HH:MM:SS). Additionally, I need to convert 220703 into 22-07-03 (YY:MM:DD).

I will add an example of my code below:

CPLF_data$HMS <- substr(as.POSIXct(sprintf(".0f", CPLF_data$StartTime), format='%H%M%S'), 12, 16)

CPLF_data$YMD <- as.POSIXct(CPLF_data$Date, tz="UTC", origin ="1970-01-01", format ="%Y-%M-%D")

The first line is correct however, it does not show seconds. The second line is incorrect.

Thank you.

an example of what I want my data to look like, this is not perfect as I am still having trouble with the code

I want my final product to be a new column with the times and dates in the correct format with their own columns.

CodePudding user response:

Try the ymd_hms function in the lubridate package.

output$datetime <- ymd_hms(paste(input$year, input$month, input$day, input$HH, input$MM, input$SS, sep="-"))

You can enter 00 if you don't have seconds, for example ....

CodePudding user response:

Base R does not have a class for just "time" (of day), as.POSIXct doesn't deal with "times", it deals with "date-times". The lubridate:: package does give number-like HMS values, which may be relevant, but since each row has both date and time, it seems relevant to combine them instead of putting them into separate columns.

transform(CPLF_data, StartTime = as.numeric(StartTime), Date = as.numeric(Date)) |>
  transform(
    DateTime = ISOdate(
      2000   Date %/% 10000, (Date %% 10000) %/% 100, Date %% 100,
      StartTime %/% 10000, (StartTime %% 10000) %/% 100, StartTime %% 100)
  )
#   StartTime   Date            DateTime
# 1     93537 220703 2022-07-03 09:35:37
  •  Tags:  
  • r
  • Related