Remove seconds from time in R
Asked Answered
S

6

6

I am trying to remove the seconds from a column of hours in POSIXct format:

#"2016-04-02 10:33:45 COT" "2016-04-02 22:19:24 COT"
#"2016-04-09 17:47:13 COT" "2016-04-13 16:56:23 COT"

x <- structure(c(1459589625, 1459631964, 1460220433, 1460562983),
     class = c("POSIXct", "POSIXt"), tzone = "")

I am trying this but I am not seeing results:

y <- as.POSIXct(x, format = "%d/%m/%Y %H:%M")
Schecter answered 28/9, 2016 at 19:58 Comment(0)
I
9

No you are giving as.POSIXct a wrong format...

What about using format

datetimes = as.POSIXct(c("2016-04-02 10:33:45 COT", "2016-04-02 22:19:24 COT" ,"2016-04-09 17:47:13 COT", "2016-04-13 16:56:23 COT")    
format(datetimes,format='%Y%m%d %H:%M')

[1] "20160402 10:33" "20160402 22:19" "20160409 17:47" "20160413 16:56"
Instancy answered 28/9, 2016 at 20:1 Comment(1)
Seem to be missing a right parenthesis on the first line. Not a big deal, still very helpful!Corinacorine
D
8

you can use round.POSIXt:

round(Sys.time(), units = "mins")
#"2017-01-30 11:20:00 CET"
Dishtowel answered 30/1, 2017 at 10:21 Comment(1)
If you use this function to manipulate a data.frame you need an extra as.POSIXct to remove the list structureDishtowel
M
1

This is what you have:

x <- structure(c(1459589625, 1459631964, 1460220433, 1460562983),
     class = c("POSIXct", "POSIXt"), tzone = "")

This is what you want:

x <- format(as.POSIXct(x), "%d-%m-%Y %H:%M")
x

[1] "02-04-2016 15:03" "03-04-2016 02:49" "09-04-2016 22:17" "13-04-2016 21:26"
Millihenry answered 11/9, 2017 at 16:20 Comment(0)
W
0

If you want to round date to minutes you can do this:

   x <- as.POSIXlt(c("2016-04-02 10:33:45 COT"))
   res <-as.POSIXlt(floor(as.double(x) / 60) * 60, origin = '1970-01-01')
   res
   #  "2016-04-02 10:33:00 BST"
Withers answered 28/9, 2016 at 20:5 Comment(1)
See %/% to simplify the expression a bit.Gilbertgilberta
L
0

Just use substring:

datetimes <- c("2016-04-02 10:33:45 COT", "2016-04-02 22:19:24 COT" ,
               "2016-04-09 17:47:13 COT", "2016-04-13 16:56:23 COT")

as.POSIXct(substring(datetimes, 1, nchar(datetimes[1])-7))   

#[1] "2016-04-02 10:33:00 IST" "2016-04-02 22:19:00 IST" 
#    "2016-04-09 17:47:00 IST" "2016-04-13 16:56:00 IST"

# without timezone
format(substring(datetimes, 1, nchar(datetimes[1])-7), 
                 format='%Y-%m-%d %H:%M:%S', usetz = FALSE)
#[1] "2016-04-02 10:33" "2016-04-02 22:19" "2016-04-09 17:47" "2016-04-13 16:56"
Lisle answered 28/9, 2016 at 20:27 Comment(1)
The timezone string shown does not lead to confidence here.Gilbertgilberta
U
0
lubridate::floor_date(datetimes, unit = "minutes")
Ungrudging answered 15/10 at 23:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.