14

This question might be simple for some of you but bear with me since I'm a beginner in R.

I have a dataframe that has a factor column (called time) containing DateTime data as the following:

time
01/01/2011 00:10
02/01/2011 03:00
03/01/2011 05:00
04/01/2011 10:03

I want to convert this column into DateTime column in R. I searched and tried some functions but it gives me 'NA' results. The following functions are those I tried:

> dataframe1$datetime <- as.POSIXlt(as.character(dataframe1$time), format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.POSIXlt(strptime(dataframe1$time), format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.POSIXlt(dataframe1$time, format="%d/%m/%Y %H:%M")
> dataframe1$datetime <- as.chron(dataframe1$time, "%d/%m/%Y %H:%M")

I don't know what else to try. I want ideally to add three columns namely datetime, date, and time.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Fatma S
  • 185
  • 1
  • 1
  • 9

2 Answers2

19

Try:

dataframe1$datetime <- strptime(x = as.character(dataframe1$datetime),
                                format = "%d/%m/%Y %H:%M")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    I was able to extrat the date but not the time. I used `dataframe1$datetime <- strptime(x = as.character(dataframe1$datetime), format = "%H:%M")` any idea? – Fatma S Apr 15 '14 at 22:34
  • To my knowledge there isn't a class of date/time for just H-M-S; your choices are Y-M-D or Y-M-D-H-M-S-etc-etc. If you find one, though, I'd love to find out about it! –  Apr 15 '14 at 22:46
  • 1
    I found a solution `dataframe1$time <- format(dataframe1$datetime, "%H:%M:%S")` :) – Fatma S Apr 16 '14 at 12:35
2

Probably the easiest thing to do is use the lubridate packages which has a large number of functions for date manipulation. The following will convert your time into a POSIXct object:

 library(lubridate)
 mdy_hm( as.character(dataframe1$time) )

See ?mdy to see the variety of date parsing functions.

For a slightly more verbose version that does not rely on lubridate

strptime(x = as.character( dataframe1$datetime ), format = "%d/%m/%Y %H:%M")
ctbrown
  • 2,271
  • 17
  • 24