-1

I need to split the variable date and time to date and time as per below format. I tried removing T using gsub with space and then I got the output as below but not as per my requirement? Is there any way to get time in required format?

Got output:

Time 
13H 00M 0S

Desired Output:

Date and time          Date         Time
2018-09-21T13:00    2018-09-21      13:00:00
2019-12-24T09:07    2019-12-24      09:07:00
2020-01-24T12:28    2020-01-24      12:28:00
Waldi
  • 39,242
  • 6
  • 30
  • 78
Learner
  • 47
  • 8
  • No. It doesn't solve my problem – Learner Jul 28 '20 at 08:24
  • No, it didn't work for me ...I separated the dateandtime varibale to time but i didnt get the exact format. I understand that i can replace 13H 00M 0S (HMS) with : to get the required output (13:00:00) using gsub, but i want something which automatically populates the desired output shown above – Learner Jul 28 '20 at 08:41
  • What format do you have in `Date and time` column is it `2018-09-21T13:00` or `13H 00M 0S`? – A. Suliman Jul 28 '20 at 08:44
  • In Dateandtime column i have 2018-09-21T13:00, but i splited it into date and time. My output was 2018-09-21 (Date) and 13H 0M 0S in time column. My question is how to convert the time (13H 0M 0S) to 13:00:00 (in this format). Is there any particular way to automatically convert from 13H 0M 0S to the desired format (13:00:00)? – Learner Jul 28 '20 at 08:50
  • Please add first few rows of your data using `dput` to avoid confusion and clarification in comments. Use `dput(head(df))`. – Ronak Shah Jul 28 '20 at 08:55
  • I got the desired output using lubridate package. library(lubridate) hms::hms(time) It converts the 13H 00M 0S to 13:00:00 – Learner Jul 28 '20 at 08:58

2 Answers2

0

If your data is something like this :

df <- structure(list(Date_and_time = c("2018-09-21T13:00", "2019-12-24T09:07", 
"2020-01-24T12:28")), row.names = c(NA, -3L), class = "data.frame")
df
#     Date_and_time
#1 2018-09-21T13:00
#2 2019-12-24T09:07
#3 2020-01-24T12:28

You can get data in desired format by doing :

library(dplyr)

df %>%
   mutate(Date_and_time = lubridate::ymd_hm(Date_and_time), 
          Date = as.Date(Date_and_time), 
          Time = format(Date_and_time, "%H:%M:%S"))

#        Date_and_time       Date     Time
#1 2018-09-21 13:00:00 2018-09-21 13:00:00
#2 2019-12-24 09:07:00 2019-12-24 09:07:00
#3 2020-01-24 12:28:00 2020-01-24 12:28:00

This can also be done using base R :

df$Date_and_time <- as.POSIXct(df$Date_and_time, format = "%Y-%m-%dT%H:%M")

transform(df, Date = as.Date(Date_and_time), 
              Time = format(Date_and_time, "%H:%M:%S"))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

I got the desired output using lubridate package.

library(lubridate) hms::hms(time)

It converts the 13H 00M 0S to 13:00:00

Learner
  • 47
  • 8