1

String: "12/27/2020 00:00:00"

I'd like this to be formatted as a date. Tried:

library(lubridate)
parse_date_time('12/27/2020 00:00:00', mdy)
Error in as.character(x) : 
  cannot coerce type 'closure' to vector of type 'character'

Then tried:

mdy('12/27/2020 00:00:00')
[1] NA
Warning message:
All formats failed to parse. No formats found. 

Then tried:

as_date('12/27/2020 00:00:00')
[1] NA
Warning message:
All formats failed to parse. No formats found. 

How can I turn this string into a date?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

1 Answers1

1

We can use format in as.Date from base R as

as.Date(str1, "%m/%d/%Y")
#[1] "2020-12-27"

Or if we need the parse_date_time, specify the format as a string

parse_date_time('12/27/2020 00:00:00',  'mdy HMS')
#[1] "2020-12-27 UTC"

To convert to Date class, wrap with as.Date or as_date

as_date(parse_date_time('12/27/2020 00:00:00',  'mdy HMS'))
#[1] "2020-12-27"

Or

mdy_hms('12/27/2020 00:00:00')
#[1] "2020-12-27 UTC"

With the format in tidyverse, it needs to match the full format. Here, we have Hour:Minute:Seconds as well, so we need the _hms


Or this can be automatically picked up with anydate

library(anytime)
anydate('12/27/2020 00:00:00')
#[1] "2020-12-27"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks. Using tidyverse format with `mdy_hms` is it possibel to then extract just the date part and have it formatted as a date? i.e. drop the hms? – Doug Fir Dec 20 '20 at 19:07
  • 1
    @DougFir After doing the `parse_date_time`, you can wrap with `as.Date` or `as_date` – akrun Dec 20 '20 at 19:07