1

I have a csv file which has date in following format.

date<-c("2018-08-11 03-PM","2018-02-11 05-AM","2018-08-11 01-AM")

How can I convert it to Date in order to sort them by day and time?

ToToRo
  • 373
  • 1
  • 5
  • 12
  • Once they're of type `Date`, just sort as you'd sort any variable: [How to sort a data frame by date](https://stackoverflow.com/q/6246159/8366499) – divibisan Mar 14 '19 at 15:38
  • It looks I can't set the time correct and get "2018-08-11 01-AM" before "2018-08-11 03-PM". Thoughts? – ToToRo Mar 14 '19 at 16:44
  • Parsing dates and times is really finicky. It's probably not understanding the "hour-AM/PM" properly. Take a look at `?lubridate::parse_date_time` for all the different format codes you can use. You might have to play around a bit to get it to read it properly. For the time part, you might want something like: `"... H-Op"` – divibisan Mar 14 '19 at 16:47

1 Answers1

0

One line solution-

date<-sort(as.Date(c("2018-08-11 03-PM","2018-02-11 05-AM","2018-08-11 01-AM")))

Edit:

you need to remove - from time part-

date <- stringi::stri_replace_last_fixed(date, '-', ' ')
sort(lubridate::ydm_h(date))
Rushabh Patel
  • 2,672
  • 13
  • 34
  • but this only show date without time, I am thinking to write like ` date<-sort(as.Date(c("2018-08-11 03-PM","2018-02-11 05-AM","2018-08-11 01-AM"),format="%d/%m/%Y%H"))` but it does not work – ToToRo Mar 14 '19 at 16:42
  • Check above solution!! – Rushabh Patel Mar 14 '19 at 17:08