steves
steves

Reputation: 331

R Convert and split string to date and time?

I have the following structure of my datetime column in my df dataframe:

YYYYmmddhhmmss, for example: "20171204211500".

I have tried using split and substring, is there any way to do it fast and efficient?

And I have checked the site for similar questions but it's not the same.

Upvotes: 0

Views: 231

Answers (2)

Suanbit
Suanbit

Reputation: 491

Use lubridate package

library (lubridate)

date<- "20171204211500"
date_ok <- ymd_hms(date)
date_ok
[1] "2017-12-04 21:15:00 UTC"

Any doubts, just tell me

Upvotes: 2

akrun
akrun

Reputation: 887981

We can use as.POSIXct to convert to a Date time object

out <- as.POSIXct(str1, format = "%Y%m%d%H%M%S")
out
#[1] "2017-12-04 21:15:00 IST"

From this, we can convert to Date object with as.Date

as.Date(out)

and also extract the time component with format

format(out, "%H:%M:%S")

data

str1 <- "20171204211500"

Upvotes: 4

Related Questions