3

I have df$date as character type below:

     date
1    "2016-04-10T12:21:25.4278624" 
2    "2016-04-12T10:01:42.9573987" 
3    "2016-04-12T10:02:15.2168753" 
4    "2016-04-12T10:02:45.3005686"

I want to convert it to datetime object and tried as.Date(df$date) and the output is

"2016-04-10" 
"2016-04-12" 
"2016-04-12" 
"2016-04-12"

I also tried as.POSIXlt(df$date) and the output is

"2016-04-10 BST" 
"2016-04-12 BST" 
"2016-04-12 BST" 
"2016-04-12 BST"

What I am looking for is

     date
1    2016-04-10 12:21:25.4278624 
2    2016-04-12 10:01:42.9573987 
3    2016-04-12 10:02:15.2168753 
4    2016-04-12 10:02:45.3005686

I also tried the following from the help

as.POSIXct(strptime("2011-03-27 01:30:00", "%Y-%m-%d %H:%M:%S"))

The output is NA

How do I get the desired output?

figurine
  • 716
  • 8
  • 21
chintan s
  • 5,052
  • 13
  • 40
  • 71

2 Answers2

7

For me it works like this:

test <- "2016-04-10T12:21:25.4278624"
z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS")

#output:
z
"2016-04-10 12:21:25 CEST"

The code is form here: converting datetime string to POSIXct date/time format in R

Community
  • 1
  • 1
Mario
  • 1,789
  • 11
  • 28
3

Another solution would be using the lubridate package.

 library(lubridate)
 test <- "2016-04-10T12:21:25.4278624"

You can use the ymd_hms function and don't have to worry about the formats in this case.

ymd_hms(test)

#output
[1] "2016-04-10 12:21:25 UTC"

You can change the timezone using the tz parameter.

ymd_hms(test, tz = "EST")
[1] "2016-04-10 12:21:25 EST"
krish
  • 1,160
  • 2
  • 13
  • 26