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
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"
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"
v1 <- c("00:43:43", "02:24:58")
One option is to use format to format the datetimes into an expression and then evaluate it.
sapply(format(df$Datetime, '%H*60 + %M'), function(x) eval(parse(text = x)))
# 00*60 + 43 02*60 + 24
# 43 144
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With