How to convert a String to Date in R

后端 未结 3 1794
栀梦
栀梦 2021-01-29 12:25

Is there any way to convert below string to a standard R date class object?

Date_String = \"19th January 2020\"

Any pointer appreciated.

相关标签:
3条回答
  • 2021-01-29 13:08
        Date_String <- "19th January 2020"
    
        # Using BASE R
        Date_String <- sub("st|nd|rd|th", "", Date_String)
        as.Date(Date_String, format = "%d %B %Y")
        #> [1] "2020-01-19"
    
        # Using Lubridate package
        lubridate::dmy(Date_String)
        #> [1] "2020-01-19"
    
    0 讨论(0)
  • 2021-01-29 13:13

    In base R:

    # Make sure your locale is English
    Sys.getlocale() # can update with Sys.setlocale(LC_TIME = 'en_US.UTF-8')
    
    # Remove "th", more generally the first sequence of lower-case letters
    Date_String <- sub("[a-z]+", "", Date_String)
    # Now specify the format for as.Date()
    as.Date(Date_String, format = "%d %B %Y")
    [1] "2020-01-19"
    
    0 讨论(0)
  • 2021-01-29 13:18

    Lubridate can handle it:

    > Date_String <- "19th January 2020"
    > lubridate::dmy(Date_String)
    [1] "2020-01-19"
    
    0 讨论(0)
提交回复
热议问题