plshelp
plshelp

Reputation: 273

How to format a time in R

I have been given a dataset that lists date and time separately. The dates are fine however the time is being treated as a character rather than a date/time object.

The current time column looks like "13:00", "13:05", "13:10" etc.

I tried mutating the column using as.POSIXct() however it changed the column to all NA.

This was my attempt:

data = data %>%
    mutate(time = as.POSIXct(time, format = "h:m"))

I expected a similar looking column but instead of strings I wanted it to be times/dates. Thanks for any help!

Upvotes: 5

Views: 9413

Answers (3)

Jim
Jim

Reputation: 578

For a simple, non package solution:

I would first create a column with both the date and time in it

dateandtime <- as.character(paste(date, time, sep = ' '))

and then use the strptime function:

dateandtime <- strptime(dateandtime,
                        format = "%Y-%m-%d %H:%M",
                        tz = 'GMT')

just put the dataframe name in front of all variables, e.g.:

df$dateandtime <- as.character(paste(df$date, df$time, sep = ' '))

Hope it helps!

Upvotes: 3

G. Grothendieck
G. Grothendieck

Reputation: 269451

The times class in chron can represent times without dates:

library(chron)
library(dplyr)

# input data
data <- data.frame(date = "2000-01-01", time = c("13:00", "13:05", "13:10"))

data %>%
  mutate(date = as.chron(as.character(date)),
         time = times(paste0(time, ":00")),
         datetime = chron(date, time))

giving:

      date     time            datetime
1 01/01/00 13:00:00 (01/01/00 13:00:00)
2 01/01/00 13:05:00 (01/01/00 13:05:00)
3 01/01/00 13:10:00 (01/01/00 13:10:00)

Upvotes: 3

clemens
clemens

Reputation: 6813

If you use as.POSIXct, you need to provide the format differently:

as.POSIXct("13:05", format = "%H:%M")

This however returns [1] "2019-03-26 13:05:00 CET" since date/times are represented as calendar dates plus time to the nearest second.

If you only want to use the time, you could use data.table::asITime:

data.table::as.ITime(c("13:00", "13:05", "13:10"))

This returns:

str(data.table::as.ITime(c("13:00", "13:05", "13:10")))
'ITime' int [1:3] 13:00:00 13:05:00 13:10:00

Upvotes: 1

Related Questions