mustafa
mustafa

Reputation: 223

Is there a way in R to convert my DateTime column into Date and Time with the format ("%m/%d/%Y" and "%h/%m/%s")

I have the following data df that includes the Date Time Column:

structure(list(DateTime = structure(c(1L, 2L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 36L, 37L, 38L, 39L, 39L, 40L, 41L, 42L, 43L, 44L, 20L, 45L, 46L, 3L, 4L, 5L, 6L, 7L), .Label = c("4/1/2015 0:02", "4/1/2015 1:47", "4/1/2015 10:01", "4/1/2015 10:06", "4/1/2015 10:09", "4/1/2015 10:10", "4/1/2015 10:12", "4/1/2015 2:40", "4/1/2015 5:32", "4/1/2015 6:06", "4/1/2015 6:12", "4/1/2015 7:00", "4/1/2015 7:04", "4/1/2015 7:12", "4/1/2015 7:14", "4/1/2015 7:20", "4/1/2015 7:21", "4/1/2015 7:22", "4/1/2015 7:26", "4/1/2015 7:31", "4/1/2015 7:37", "4/1/2015 7:50", "4/1/2015 7:55", "4/1/2015 8:00", "4/1/2015 8:07", "4/1/2015 8:12", "4/1/2015 8:16", "4/1/2015 8:22", "4/1/2015 8:25", "4/1/2015 8:28", "4/1/2015 8:29", "4/1/2015 8:51", "4/1/2015 8:52", "4/1/2015 8:55", "4/1/2015 8:59", "4/1/2015 9:00", "4/1/2015 9:05", "4/1/2015 9:16", "4/1/2015 9:18", "4/1/2015 9:19", "4/1/2015 9:26", "4/1/2015 9:29", "4/1/2015 9:30", "4/1/2015 9:46", "4/1/2015 9:52", "4/1/2015 9:57" ), class = "factor")), class = "data.frame", row.names = c(NA, -48L))

Upvotes: 0

Views: 143

Answers (2)

akrun
akrun

Reputation: 887118

We can use as.POSIXct from base R

df1$DateTime <- as.POSIXct(df1$DateTime, format = "%m/%d/%Y %H:%M")

Or with mdy_hm from lubridate

library(lubridate)
mdy_hm(df1$DateTime)

If we need two columns

library(dplyr)
df1 <- df1 %>%
         mutate(DateTime = mdy_hm(DateTime),
               Date = as.Date(DateTime),
               Time = strftime(DateTime, "%H:%M:%S"))

Or using anytime

library(anytime)
anytime(df1$DateTime)

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

You can use as.POSIXct/strptime in base R

as.POSIXct(x$DateTime, format = "%m/%d/%Y %H:%M", tz = "UTC")
#OR
#strptime(x$DateTime, format = "%m/%d/%Y %H:%M", tz = "UTC")

Or

lubridate::mdy_hm(x$DateTime)

If two separate columns are needed for Date and Time, we can do

x$DateTime <- as.POSIXct(x$DateTime, format = "%m/%d/%Y %H:%M", tz = "UTC")
transform(x, Date = as.Date(DateTime), Time = format(DateTime, "%T"))


#              DateTime       Date     Time
#1  2015-04-01 00:02:00 2015-04-01 00:02:00
#2  2015-04-01 01:47:00 2015-04-01 01:47:00
#3  2015-04-01 02:40:00 2015-04-01 02:40:00
#4  2015-04-01 05:32:00 2015-04-01 05:32:00
#5  2015-04-01 06:06:00 2015-04-01 06:06:00
#6  2015-04-01 06:12:00 2015-04-01 06:12:00
#....

Upvotes: 4

Related Questions