Home > database >  R base package - calculating time from character string
R base package - calculating time from character string

Time:02-05

is there any possibility to get time only from character string like "2021-09-13T16:40"?

I get it from lubridate or hms but my question is if I can get it with base R only.

I don't want to use format() because I want to have it with class: "hms" "difftime".

Thank you

CodePudding user response:

Since the "hms" class is built with items off similar structure to items of class "difftime", you can first build a difftime item and then coerce its class. The units parameter must be given as 'secs' because the hms class does not support other units.

z <- "2021-09-13T16:40"
zdt  <- strptime(z, "%Y-%m-%dT%H:%M")

# Subtract the datetime value at midnight from the starting value
dzdt <- difftime( zdt ,strptime(z, "%Y-%m-%d") , units="secs")
# Then coerce
class(dzdt)<- c("hms", "difftime")
# Now it will be recognized by the `print.hms` function
dzdt
16:40:00

CodePudding user response:

Please check the below code

library(stringr)
library(hms)
library(lubridate)

string <- "2021-09-13T16:40"
hms::as_hms(as.POSIXct(str_extract(string,'(?<=T).*'), format='%H:%M'))

Created on 2023-02-04 with reprex v2.0.2

16:40:00

CodePudding user response:

You could use strptime first to get the right format and after that use strftime to get the time you want:

string <- "2021-09-13T16:40"
strftime(strptime(string, format = "%Y-%m-%dT%H:%M"), '%H:%M')
#> [1] "16:40"

Created on 2023-02-04 with reprex v2.0.2

  •  Tags:  
  • r
  • Related