1

I am working with large datasets and in which one column is represented as char data type instead of a DateTime datatype. I trying it convert but I am unable to convert it.

Could you please suggest any suggestions for this problem? it would be very helpful for me

Thanks in advance

code which i am using right now

c_data$dt_1 <- lubridate::parse_date_time(c_data$started_at,"ymd HMS")

getting output:

2027- 05- 20 20:10:03 

but desired output is

2020-05-20 10:03
Nikhil
  • 61
  • 6
  • Hi, please share a reproducible sample of your data set with `dput(head(data))`. – Anoushiravan R Aug 27 '21 at 11:15
  • How are you importing the file ? If you specify colclasses() type into character this will help solve this when converting to date. It might be reading the field as a number which is what causing the issue. – M Daaboul Aug 27 '21 at 11:18
  • 1
    Welcome to Stackoverflow, this may address your circumstance [change order](https://stackoverflow.com/questions/44150501/combine-day-month-year-hour-to-date-time-in-r), HTH. – Chris Aug 27 '21 at 14:49

3 Answers3

1

Here is another way using lubridate:

library(lubridate)

df <- tibble(start_at = c("27/05/2020 10:03", "25/05/2020 10:47"))

df %>%
  mutate(start_at = dmy_hms(start_at))

# A tibble: 2 x 1
  start_at           
  <dttm>             
1 2020-05-27 20:10:03
2 2020-05-25 20:10:47
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
0

In R, dates and times have a single format. You can change it's format to your required format but then it would be of type character.

If you want to keep data in the format year-month-day min-sec you can use format as -

format(Sys.time(), '%Y-%m-%d %M:%S')
#[1] "2021-08-27 17:54"

For the entire column you can apply this as -

c_data$dt_2 <- format(c_data$dt_1, '%Y-%m-%d %M:%S')

Read ?strptime for different formatting options.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Using anytime

library(dplyr)
library(anytime)
addFormats("%d/%m/%Y %H:%M")
df %>%
    mutate(start_at = anytime(start_at))

-output

# A tibble: 2 x 1
  start_at           
  <dttm>             
1 2020-05-27 10:03:00
2 2020-05-25 10:47:00
akrun
  • 874,273
  • 37
  • 540
  • 662