1

My csv file has datetime data in the format yyyy-mm-dd hh:mm:ss When I read the file using readr::read_csv(), the datetime fields are loaded into the data frame as character data. When I try to convert these columns using

as.POSIXct(data_frame["col name"], format="%Y-%m-%d %H:%M:%S")

I get an error saying do not know how to convert to class POSIXct

enter image description here

If all the data in the csv file is for times >= 12:00:00 (on 24 hour clock) read_csv() will load the data and the datetime fields are dttm objects. If I have records in the csv file with a time less than 12:00:00 read_csv() will load the data but the datetime fields are loaded as characters. Subsequently I cannot convert them to datetime in the dataframe (RStudio 2022.07.2 build 576).

M--
  • 25,431
  • 8
  • 61
  • 93
  • 6
    Try `[[` instead of `[` i.e. `as.POSIXct(test_df[["started_at"]], format="%Y-%m-%d %H:%M:%S")` as `[` returns a data.frame/tibble with single column whereas `[[` returns a vector, `as.POSIXct` expects a vector – akrun Nov 28 '22 at 01:31
  • You can use `data_frame["col name"] <- strptime(data_frame["col name"],"%m/%d/%Y %H:%M:%S")` – Md Fantacher Islam Nov 28 '22 at 03:02
  • 1
    Welcome to Stack Overflow. It will help if you [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small representative dataset in a plain text format. Images of your screen are not useful. – neilfws Nov 28 '22 at 04:19
  • using [["started_at"]] works! thanks – Charles Andrews Nov 29 '22 at 05:14

0 Answers0