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")
Thanks @akrun. I applied your code but it didn't work. I guess it was due to the format, since I have the data as Posixct, concretely in "%Y-%m-%d %H:%M%S". When I runned
df$Minute<-round(period_to_seconds(hms(df$Datetime))/60)
it gives you backNA
.@Dekike It is the format. In the post, you mentioned the format as HMS. Here, you need
ymd_hms
instead ofhms
@Dekike Please check my updated post