rdatelubridate

Text date to date in R: from this format: Wed, 23 Feb 2022 00:00:00


I have a dataset with dates formatted like this:

> head(dfed$`POSTED DATE`)
[1] NA                                               
[2] "Fri, 26 Jul 2024 00:00:00 (Brussels local time)"
[3] "Thu, 4 Jul 2024 00:00:00 (Brussels local time)" 
[4] "Tue, 5 Nov 2024 17:00:00 (Brussels local time)" 
[5] "Thu, 18 Apr 2024 00:00:00 (Brussels local time)"
[6] "Wed, 7 Dec 2022 00:00:00 (Brussels local time)" 

I want R to read them as dates so that:

Input: "Fri, 26 Jul 2024 00:00:00 (Brussels local time)"

Output: 26/07/2024

What I tried:

  1. lubridate::as_datetime gave me 'All formats failed to parse. No formats found':
> as_datetime("23 Feb 2022 00:00:00")
[1] NA
Warning message:
All formats failed to parse. No formats found. 
  1. Searching through old questions didn't help

Solution

  • A convenient tool is {anytime}:

    x <- c(
      "Fri, 26 Jul 2024 00:00:00 (Brussels local time)",
      "Thu, 4 Jul 2024 00:00:00 (Brussels local time)",
      "Tue, 5 Nov 2024 17:00:00 (Brussels local time)",
      "Thu, 18 Apr 2024 00:00:00 (Brussels local time)",
      "Wed, 7 Dec 2022 00:00:00 (Brussels local time)"
    )
    
    anytime::anydate(x)
    # [1] "2024-07-26" "2024-07-04" "2024-11-05" "2024-04-18" "2022-12-07"
    

    It seems that you don't need to reset the locale with this function.