1

I have a list of time as shown below:

"0:30:00"  "1:00:00"  "1:30:00"  "10:00:00" "10:30:00" "11:00:00" "11:30:00" "12:00:00" "12:30:00" "13:00:00" "13:30:00" "14:00:00" "14:30:00"

When I used the as.Date function to convert these into date objects in R using the following code:

time1<-as.Date(time,format='%H:%M:%S')

It gave me the following output:

"2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09" "2016-05-09"

Why is that the case? Is there something wrong with my code or the original time format?

Thanks.

A1122
  • 1,324
  • 3
  • 15
  • 35

2 Answers2

7

We can use times from chron to convert to time

library(chron)
times(v1)
#[1] 00:30:00
chron(times(v1))
#[1] (01/01/70 00:30:00)

Or use strptime to convert to date time objects

r1 <- strptime(v1, format = "%H:%M:%S")
r1
#[1] "2016-05-10 00:30:00 IST"

In addition to strptime, POSIXct is also possible

r2 <- as.POSIXct(v1, format = "%H:%M:%S")
r2
#[1] "2016-05-10 00:30:00 IST"

The difference between strptime and POSIXct is that the former has POSIXlt class whereas the latter have only POSIXct. Also, if we look at the structure of both, the strptime is stored as a list

is.list(r1)
#[1] TRUE
is.list(r2)
#[1] FALSE
lapply(r1, I)
r1$min
#[1] 30

Another option is lubridate

library(lubridate)
hms(v1)
#[1] "30M 0S"

This also have the date i.e. current date.

The as.Date only converts to 'Date'. It doesn't show any time.

data

v1 <- "0:30:00"
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks Akrun. I tried Chron and it works perfectly. I have a dataset with many columns, of which Time is one of them. I would like to convert this column to Chron object and then sort the dataset by Time. Is this possible? – A1122 May 10 '16 at 05:17
  • @A1122 I think after you create the column with `chron`, use `order` i.e. `df1$Time <- chron(times(df1$yourcolumn)); df1[order(df1$Time),]` – akrun May 10 '16 at 05:20
2

You can also use as.POSIXct

x <- c("0:30:00",  "1:00:00",  "1:30:00",  "10:00:00", "10:30:00", "11:00:00" ,"11:30:00", "12:00:00", "12:30:00", "13:00:00", "13:30:00", "14:00:00", "14:30:00")

as.POSIXct(x,format="%H:%M:%S")

#[1] "2016-05-10 00:30:00 IST" "2016-05-10 01:00:00 IST" "2016-05-10 01:30:00 IST" "2016-05-10 10:00:00 IST"
#[5] "2016-05-10 10:30:00 IST" "2016-05-10 11:00:00 IST" "2016-05-10 11:30:00 IST" "2016-05-10 12:00:00 IST"
#[9] "2016-05-10 12:30:00 IST" "2016-05-10 13:00:00 IST" "2016-05-10 13:30:00 IST" "2016-05-10 14:00:00 IST"
#[13] "2016-05-10 14:30:00 IST"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213