Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the minute of the day with R?

Tags:

r

lubridate

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

like image 281
Dekike Avatar asked Jan 22 '26 22:01

Dekike


2 Answers

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")
like image 85
akrun Avatar answered Jan 25 '26 20:01

akrun


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
like image 42
IceCreamToucan Avatar answered Jan 25 '26 21:01

IceCreamToucan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!