0

Hi I have date_time column as "Factor" type which is having mixed date_time as below. How to change these informats to R datetime format

date_time                  R_date_time
01-Apr-2017 12:00:00       2017-04-01 12:00:00 
02/04/2017  03:00:00       2017-04-02 03:00:00 
30/05/2017  06:15:00       2017-05-30 06:15:00
2/4/2017    05:18:00       2017-04-02 05:18:00
2017/12/31  20:30:00       2017-12-31 20:30:00
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user5860640
  • 71
  • 2
  • 7

2 Answers2

0

You can use lubridate:

> dmy_hms("01-Apr-2017 12:00:00")
[1] "2017-04-01 12:00:00 UTC"

> dmy_hms("02/04/2017  03:00:00")
[1] "2017-04-02 03:00:00 UTC"

> dmy_hms("30/05/2017  06:15:00")
[1] "2017-05-30 06:15:00 UTC"

> ymd_hms("2017/12/31  20:30:00 ")
[1] "2017-12-31 20:30:00 UTC"

> dmy_hms("2/4/2017    05:18:00")#ambiguous format you can use mdy_hms as well
[1] "2017-04-02 05:18:00 UTC"

OR:

> mdy_hms("2/4/2017    05:18:00")
[1] "2017-02-04 05:18:00 UTC"

>ymd_hms("2017/12/31  20:30:00")
[1] "2017-12-31 20:30:00 UTC"
amonk
  • 1,769
  • 2
  • 18
  • 27
0

The anytime package is a great alternative. For instance:

date_time <- c(text = "01-Apr-2017 12:00:00", "02/04/2017 03:00:00", 
               "30/05/2017 06:15:00", "2/4/2017 05:18:00", "2017/12/31 20:30:00")

You need to add some of the formats using addFormats() e.g.:

library(anytime)
anytime::addFormats(c("%d/%m/%Y %H:%M:%S")) 

anytime(date_time, tz = "UTC")

[1] "2017-04-01 12:00:00 UTC" "2017-04-02 03:00:00 UTC" "2017-05-30 06:15:00 UTC"
[4] NA                        "2017-12-31 20:30:00 UTC"

However, it seems like anytime() can't parse those like "2/4/2017 05:18:00". See e.g. https://github.com/eddelbuettel/anytime/issues/24. In that case you could use lubridate:dmy_hms("2/4/2017 05:18:00") or simply strptime("2/4/2017 05:18:00", format = "%d/%m/%Y %H:%M:%S", tz = "UTC")

Edgar Santos
  • 3,426
  • 2
  • 17
  • 29
  • The results from `anytime(R_date_time, tz = "UTC")` Don't look like the input dates; e.g. `01-Apr-2017 12:00:00` becoming `2017-03-31 22:00:00 UTC`. I suspect it's a timezone thing, but not sure. – Marijn Stevering May 22 '17 at 09:44
  • @MarijnStevering, It works well for me: anytime("01-Apr-2017 12:00:00", asUTC = TRUE, tz = "UTC") #"2017-04-01 12:00:00 UTC". – Edgar Santos May 22 '17 at 09:50