0

I have date data formatted in an odd way that I would like to clean up in R.

The dates are in format "d-Mon-y hh:mm:sec AM". For example "1-Feb-05 12:00:00 AM". The day and time are useless to me, however I would like to be able to use the month and year while also converting them to date-time format.

I cannot figure out how to do this.

zx8754
  • 52,746
  • 12
  • 114
  • 209
gm5991
  • 1
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap May 09 '18 at 19:38
  • 1
    `zoo::as.yearmon(as.Date("1-Feb-05 12:00:00 AM", "%d-%b-%y"))`? or `format(as.Date("1-Feb-05 12:00:00 AM", "%d-%b-%y"), '%Y %b')`? – Jaap May 09 '18 at 19:38

1 Answers1

0

Here is a way to do it with handy lubridate parsers and extractors. First convert the string into a datetime and then extract the month and the year:

library(tidyverse)
library(lubridate)
tibble(datetime = "1-Feb-05 12:00:00 AM") %>%
  mutate(
    datetime = dmy_hms(datetime),
    year = year(datetime),
    month = month(datetime)
    )
#> # A tibble: 1 x 3
#>   datetime             year month
#>   <dttm>              <dbl> <dbl>
#> 1 2005-02-01 00:00:00  2005     2

Created on 2018-05-09 by the reprex package (v0.2.0).

Calum You
  • 14,687
  • 4
  • 23
  • 42