Hi,
You do not need to use third party packages for date or date/time objects in R.
If you review ?as.Date, you will see that there are two default formats for Date
objects that are specified in the 'tryFormats' argument:
??tryFormats = c("%Y-%m-%d", "%Y/%m/%d")
If your date character vector does not conform to either one, which it does not
in this case, then you need to explicitly specify the input format, the details
of which are specified in ?strptime.
Thus:
> as.Date("12 APR 2023", format = "%d %b %Y")
[1] "2023-04-12"
> str(as.Date("12 APR 2023", format = "%d %b %Y"))
?Date[1:1], format: "2023-04-12"
> class(as.Date("12 APR 2023", format = "%d %b %Y"))
[1] "Date"
where the %d defines the day of the month number, %b defines the abbreviated
month and %Y defines the four digit year. The spaces in between each specifier
in the format argument reflect that there are spaces in the source vector, as
opposed to hyphens (e.g. 12-APR-2023) or slashes (e.g. 12/APR/2023).
Note that once your vector is a Date class object, you can then manipulate them
as dates and perform various operations on them. You can then use format() to
alter the output format as you may need for other purposes, in which case, the
formatted output is coerced back to a character vector, even though the internal
storage is still a Date class object.
Regards,
Marc Schwartz
On April 12, 2023 at 10:34:26 AM, akshay kulkarni (akshay_e4 at hotmail.com
(mailto:akshay_e4 at hotmail.com)) wrote:
> dear members,
> I want to convert "12 APR 2023" into a Date object. I tried
as_Date() from lubridate, but it is not working:
>
> > as_date("12 APR 2023")
> [1] NA
> Warning message:
> All formats failed to parse. No formats found.
> > as_date("12-APR-2023")
> [1] NA
> Warning message:
> All formats failed to parse. No formats found.
>
> I am looking for a shorthand way of doing it. Of course, one can convert
APR to 4 and get the job done, but I ma looking for a short and elegant code
>
> please help...
>
> THanking you,
> Yours sincerely,
> AKSHAY M KULKARNI
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.