2

How can I convert from a timestamp like this:

aDate <- "9-Apr-17 10:00:00 PM"
convert <- as.Date(aDate, "%d-%b-%y %H:%M:%S")

Right now, convert gives NA.

George
  • 5,808
  • 15
  • 83
  • 160
  • I can't reproduce the error. Are you sure that you defined `aDate` as above? – Eldioo Jun 16 '17 at 12:29
  • Because of [your `locale`?](https://stackoverflow.com/questions/13726894/strptime-as-posixct-and-as-date-return-unexpected-na) – Henrik Jun 16 '17 at 12:29
  • you may want to use `as.IDate` or `as.POSIXct` – akash87 Jun 16 '17 at 12:32
  • @Henrik:The locale fixes this!But it gives me only `"2017-04-09".I have to use `strptime(as.character(aDate), "%d-%b-%y %H:%M:%S")` but then I have to convert to Date format which again shows only the date – George Jun 16 '17 at 12:49
  • @George I don't understand what mean by '_only_ "2017-04-09"'. Your title suggests that you wanted a `Date`. – Henrik Jun 16 '17 at 14:13
  • @Henrik:Yes, but with time format also as I have in post (as.Date(aDate, "%d-%b-%y %H:%M:%S")).Sorry for the incovenience. – George Jun 16 '17 at 14:14

1 Answers1

2

This should solve your problem :

format(lubridate::dmy_hms(aDate), format = "%d-%m-%y %H:%M:%S")

"09-04-17 22:00:00"

Paul Endymion
  • 537
  • 3
  • 18
  • Hmm..It works!But it gives me ` "2017-04-09 22:00:03 UTC"` instead of ` "09-04-17 22:00:03 UTC"`.And I couldn't find a way to correct this. – George Jun 16 '17 at 12:45
  • Yes, I mean I can't find how to have first the date, then month, then year. – George Jun 16 '17 at 12:50