How to change (20190717-18:00:00) char to Datetime format YYYYMMDD-HH24:MI:SS

Hi,
I am new to R. Please help how to convert the character format to Datetime format. I have the data in Excel. I want to plot a graph. please help me.

str(DB)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 52848 obs. of 68 variables:
SNAP_ID : num 87030 87030 87030 87030 87030 ... DATETIME : chr "20190717-18:00:00" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>How to convert it to Datetime format (YYYYMMDD-HH24:MI:SS)

Regards,
Sathish

Welcome to the community!

Try like this:

sample_date_in_character <- "20190717-18:00:00"

converted_to_datetime <- as.POSIXct(x = sample_date_in_character,
                                    format = "%Y%m%d-%H:%M:%S")

converted_to_datetime
#> [1] "2019-07-17 18:00:00 IST"

Created on 2019-09-28 by the reprex package (v0.3.0)

Look at the documentation of strptime for more details on the formats. There's also a separate package lubridate to handle to dates and times.

Hope this helps.

2 Likes

A lubridate approach would be

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

sample_date_in_character <- "20190717-18:00:00"
nice_date <- ymd_hms(x = sample_date_in_character)
nice_date
#> [1] "2019-07-17 18:00:00 UTC"

Created on 2019-09-30 by the reprex package (v0.3.0)

Welcome to the RStudio Community!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.