I am having a column on ( September 9, 2019 ) in this format and I want to convert September into a number format EX (September 9, 2019) = 09-09-2019. I know we can use tidyverse with mutate function but want to know if there are any other ways.
Asked
Active
Viewed 65 times
0
-
Does this answer your question? [Convert month names to numbers in r](https://stackoverflow.com/questions/59941554/convert-month-names-to-numbers-in-r) – Jan Jul 15 '23 at 09:43
-
1R's `datetime` class is an internal (numeric) representation of a date time. Do you want to change the default formatting of this internal representation, or is your data in another form - character, for example? A _minimal reproducible example_ would clarify and provide more helpful answers. You can cpnsider the `lubridate` package, which has a comprehensive suite of `datetime` utilities. – Limey Jul 15 '23 at 09:44
-
Currently, the date September 9, 2019, is in char format and I want to bring it into 09-09-2019 format. – Akshayd978 Jul 15 '23 at 09:49
-
Then it's not a `datetime`. It's a `character` string. You have several answers below. – Limey Jul 15 '23 at 10:30
2 Answers
2
If you want to convert into an actual Date
object in R you can use as.Date
as.Date("September 9, 2019", format = "%B %d, %Y")
#> [1] "2019-09-09"
If you want this printed in the particular format you have specified, it will no longer be a Date
object, but will be back to being a character
. If you intend to do calculations on the dates, it would be best to keep them in Date
format. You should only change the format to the desired character string when you come to the output stage (e.g. plotting).
The format you wanted is ambiguous, because the American style is month-day-year, whereas many other locales use day-year-month. Your question doesn't make this clear because the month and day are the same.
For American style:
as.Date("September 9, 2019", format = "%B %d, %Y") |> format("%m-%d-%Y")
#> [1] "09-09-2019"
For other locales
as.Date("September 9, 2019", format = "%B %d, %Y") |> format("%d-%m-%Y")
#> [1] "09-09-2019"

Allan Cameron
- 147,086
- 7
- 49
- 87
1
Locale is important, but basically it should work
d <- as.POSIXct("September 9, 2019", format = "%b %d, %Y")

GrBa
- 381
- 1
- 9