Home > Blockchain >  How to stop lubridate dropping the hour when it's just gone midnight
How to stop lubridate dropping the hour when it's just gone midnight

Time:09-16

How do I get lubridate to keep the hour when the time is e.g. 00:30:42? hms() wants to output 30M 42S, whereas I want 0H 32M 40S.

library(lubridate)
hms("00:32:40")
[1] "32M 40S"

The reason I need this is because I'm using the time to put together a datetime:

ymd_hms("2022-09-13 0H 40M 32S")
[1] "2022-09-13 00:40:32 UTC"
ymd_hms("2022-09-13 40M 32S")
[1] NA
Warning message:
All formats failed to parse. No formats found. 

CodePudding user response:

Depends a bit on what your original data is, as strings...

ymd("2022-09-13")   hms("00:32:40")
ymd("2022-09-13")   as.duration("32M 40S")

or as @king_of_limes already suggested in his answer:

ymd_hms(paste("2022-09-13", "00:32:40"))

All will output:

[1] "2022-09-13 00:32:40 UTC"

If we truely want to work with one string that has a time lacking the hours, we can create a ymd_ms function that is not existing in lubridate. It is a bit more robust than needed, but it supports now both (HH:)MM:SS as well as (H) M S formats.

# lets create some not existing lubridate style function ymd_ms()
ymd_ms <- function(x) {
  ymd_hms(gsub("(\\d )(\\d{1,2}M|(\\d{1,2}:\\d{1,2})$)", "\\10H \\2", x, perl = T))
}

v <- c("2022-09-13 40M 32S", "2022-09-13 3H 40M 32S", "2022-09-13 2H 40:32", "2022-09-13 12:40:32", "2022-09-13 40:32", "2022-09-13 11H 40:32 PM", "2022-09-13 11:40:32 PM", "2022-09-13 11:40:32 AM")

ymd_ms(v)

# [1] "2022-09-13 00:40:32 UTC" "2022-09-13 03:40:32 UTC" "2022-09-13 02:40:32 UTC" "2022-09-13 12:40:32 UTC" "2022-09-13 00:40:32 UTC" "2022-09-13 23:40:32 UTC" "2022-09-13 23:40:32 UTC"
# [8] "2022-09-13 11:40:32 UTC"

CodePudding user response:

If you have two strings

a <- "2022-09-13"
b <- "00:32:40"

then you can do

lubridate::ymd_hms(paste(a,b))
  • Related