Warm tip: This article is reproduced from stackoverflow.com, please click
r lubridate

How to extract the minute of the day with R?

发布于 2020-03-27 10:29:56

I have a column in df1 that summarizes the datetime in format "%Y-%m-%d %H:%M:%S" for several months. I would like to extract the minute of the day for each datetime. That is, for the time "00:43:43" the minute of the day would be "43", for the datetime "02:24:58", the minute of the day would correspond to "144". The minute of the day has to range between 1 and 1440.

I add the code to replicate the example:

df<-data.frame(Datetime=c("2019-07-03 00:43:43",  "2019-07-03 02:24:58"))
df$Datetime<- as.POSIXct(df$Datetime, formtat="%Y-%m-%d %H:%M:%S",tz="UTC")

df
             Datetime
1 2019-07-03 00:43:43
2 2019-07-03 02:24:58

Does anyone know how to do it?

Thanks in advance

Questioner
Dekike
Viewed
17
akrun 2019-07-03 23:39

An option is

library(lubridate)
round(period_to_seconds(hms(v1))/60)

If we don't want to round it

sub("\\..*", "", period_to_seconds(hms(v1))/60)
#[1] "43"  "144"

Update

In the OP's initial post, the format showed was %H:%M:%S, so we used hms. With the example showed, it would be ymd_hms

v2 <- sub(".*\\s", "", df$Datetime)
sub("\\..*", "", period_to_seconds(hms(v2))/60)
#[1] "43"  "144"

data

v1 <- c("00:43:43",  "02:24:58")