Search code examples
rdatetimeformatposixctstrptime

Converting datetime character vector into date-time format


I have tried to convert below character vector into date-time format("%Y-%m-%d %H:%M:%S") but was unable to successfully convert mid-night time-stamp. If the vector contains both date(mid-night 00:00:00) as well as date-times in the same operation. Any handy option available to do this. Please ignore character length and paste option. Thanks.

dttime=c()
dttime=c("2021-08-03 11:59:59", "2021-08-03 12:59:59", "2021-08-03", 
"2021-08-03 16:59:59")
strptime(dttime, format = "%Y-%m-%d %H:%M:%S")
[1] "2021-08-03 11:59:59 IST" "2021-08-03 12:59:59 IST" NA "2021-08-03 16:59:59 IST 
as.POSIXct(dttime, format = "%Y-%m-%d %H:%M:%S")
[1] "2021-08-03 11:59:59 IST" "2021-08-03 12:59:59 IST" NA "2021-08-03 16:59:59 IST"
format(dttime, format = "%Y-%m-%d %H:%M:%S")
[1] "2021-08-03 11:59:59" "2021-08-03 12:59:59" "2021-08-03         " "2021-08-03 16:59:59

Desired output is:

dttime
[1] "2021-08-03 11:59:59" "2021-08-03 12:59:59" "2021-08-03 00:00:00" "2021-08-03 16:59:59

Any other available existing method.

dttime[nchar(dttime)<19]=paste(dttime[nchar(dttime)<19],"00:00:00")
> dttime
 [1] "2021-08-03 11:59:59" "2021-08-03 12:59:59" "2021-08-03 00:00:00" "2021-08-03 16:59:59"

Solution

  • You can use as_datetime function from lubridate package

    library(lubridate)
    #> Warning: package 'lubridate' was built under R version 3.6.3
    #> 
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #> 
    #>     date, intersect, setdiff, union
    dttime = c("2021-08-03 11:59:59", "2021-08-03 12:59:59",
               "2021-08-03", "2021-08-03 16:59:59")
    as_datetime(dttime, tz = "UTC")
    #> [1] "2021-08-03 11:59:59 UTC" "2021-08-03 12:59:59 UTC"
    #> [3] "2021-08-03 00:00:00 UTC" "2021-08-03 16:59:59 UTC"
    

    You can change the timezone into another timezone, see ?as_datetime