Convert time / date from coefficient

I want to convert time from factor to date.

For sample data:

date.time <- structure(list(date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
                                  1L, 1L), .Label = "02/02/2013", class = "factor"), time = structure(1:9, .Label = c("07:55:40", 
                                                                                                                      "07:55:50", "07:56:00", "07:56:10", "07:56:20", "07:56:30", "07:56:40", 
                                                                                                                      "07:56:50", "07:57:00"), class = "factor")), .Names = c("date", 
                                                                                                                                                                              "time"), class = "data.frame", row.names = c(NA, -9L))

      

I want to learn how to convert datetime columns to true date / time (i.e. not factors).

Can someone please explain why this won't work?

date.time$time <- as.POSIXlt(date.time$time, format="%H:%M:%S")

      

From what I understand POSIXlt requires time and date - is that correct? When I run this code, it adds the date today.

Is it possible to: (a) convert the two columns separately to date and time columns, and (b) concatenate them together to form a time and date column?

+3


source to share


2 answers


Sorry you wanted to combine two columns. Try



date.time$date.time <- paste(as.character(date.time$date), as.character(date.time$time))
date.time$date.time <- as.POSIXlt(date.time$date.time, format="%d/%m/%Y %H:%M:%S")
date.time
class(date.time$date.time)

> date.time
        date     time           date.time
1 02/02/2013 07:55:40 2013-02-02 07:55:40
2 02/02/2013 07:55:50 2013-02-02 07:55:50
3 02/02/2013 07:56:00 2013-02-02 07:56:00
4 02/02/2013 07:56:10 2013-02-02 07:56:10
5 02/02/2013 07:56:20 2013-02-02 07:56:20
6 02/02/2013 07:56:30 2013-02-02 07:56:30
7 02/02/2013 07:56:40 2013-02-02 07:56:40
8 02/02/2013 07:56:50 2013-02-02 07:56:50
9 02/02/2013 07:57:00 2013-02-02 07:57:00
> class(date.time$date.time)
[1] "POSIXlt" "POSIXt" 

      

+2


source


you can also try the package lubridate



library(lubridate)
dmy(date.time$date)
[1] "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC"
hms(date$time)
[1] "7H 55M 40S" "7H 55M 50S" "7H 56M 0S"  "7H 56M 10S" "7H 56M 20S" "7H 56M 30S" "7H 56M 40S" "7H 56M 50S" "7H 57M 0S" 

      

+2


source







All Articles