Search code examples
rdatetimedata-conversion

From character to dates-time in R using decimal hours


I'm trying to convert characters to dates in R.

My data as the following format:

df <- data.frame(Date = c("23Jul2019 11:51:09 AM","23Jul2019 11:53:09 AM","19Jul2019 2:30:06 PM","01Aug2019 3:00:17 PM"))

Based on the solution found here: Convert character to Date in R

I could use

> as.Date(df$Date, "%d/%b/%Y %I:%M:%S %p") 
[1] NA NA NA NA

%I is for decimal hour (12h) and %p Locale-specific AM/PM (https://www.stat.berkeley.edu/~s133/dates.html) but for some reason, it returns NAs.

My goal is to sort the rows of a dataframe by date and time once dates in the character format converted to Dates in R.

What is the issue with the code I'm using?


Solution

  • This should solve it

    library(tidyverse)
    library(lubridate)
    #> 
    #> Attaching package: 'lubridate'
    #> The following object is masked from 'package:base':
    #> 
    #>     date
    df <- data.frame(Date = c("23Jul2019 11:51:09 AM","23Jul2019 11:53:09 AM","19Jul2019 2:30:06 PM","01Aug2019 3:00:17 PM"))
    
    df %>% 
      mutate(r_date_time = Date %>% dmy_hms)
    #>                    Date         r_date_time
    #> 1 23Jul2019 11:51:09 AM 2019-07-23 11:51:09
    #> 2 23Jul2019 11:53:09 AM 2019-07-23 11:53:09
    #> 3  19Jul2019 2:30:06 PM 2019-07-19 14:30:06
    #> 4  01Aug2019 3:00:17 PM 2019-08-01 15:00:17
    
    dmy_hms(df$Date) 
    #> [1] "2019-07-23 11:51:09 UTC" "2019-07-23 11:53:09 UTC"
    #> [3] "2019-07-19 14:30:06 UTC" "2019-08-01 15:00:17 UTC"
    

    Created on 2020-01-14 by the reprex package (v0.3.0)