5

I have created a file something like this:

> filesInside
         Date         Time
1  01:09:2013 10:35:49.997 
2  01:09:2013 10:35:50.197

How could I possibly make a function using

as.POSIXct()

and I should be get something like this:

> as.POSIXct("2013-09-01 10:35:50")
[1] "2013-09-01 10:35:50 NZST" 

How can I make it as a function?

My code so far:

DateTime <- as.POSIXct(paste(filesInside$Date, filesInside$Time), format="%Y%m%d %H%M%S")

Appreciate a bit of help please. Cheers

Henrik
  • 65,555
  • 14
  • 143
  • 159
jeff1234
  • 61
  • 4
  • A small reproducible example, the expected output, and what you have tried - very nice first question! +1! – Henrik Oct 25 '13 at 00:33
  • Where does the NZST come from? Should it always be NZST? – Hugh Oct 25 '13 at 00:41
  • I think this shows the local time. try the code yourself by typing `as.POSIXct("2013-09-01 10:35:50")` in R and see what code you get. Do you get something different? – jeff1234 Oct 25 '13 at 01:36

2 Answers2

3

You may try this. The order of date-time components and separators in format should reflect those in the object to be converted. See also ?strptime.

with(filesInside,
     as.POSIXct(paste(Date, Time),
                format = "%d:%m:%Y %H:%M:%S",
                tz = "NZ"))
# [1] "2013-09-01 10:35:49 NZST" "2013-09-01 10:35:50 NZST"
Henrik
  • 65,555
  • 14
  • 143
  • 159
2
library(lubridate)
dmy_hms(apply(filesInside, 1, paste, collapse=" "), tz="NZ")
# [1] "2013-09-01 10:35:49 NZST" "2013-09-01 10:35:50 NZST"

lubridate here is a cinch, especially with its collection of dmy_hms, ymd etc functions.

To properly paste across rows, simply use apply(<data.frame>, 1, paste, collapse=" ")

Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178