Valerie S
Valerie S

Reputation: 927

Replace dashes with colon in part of string

I have a dataframe with date and time values as characters, as extracted from a database. Currently the date/time looks like this: 2017-03-17 11-56-20

I want it to loook like this 2017-03-17 11:56:20

It doesn't seem to be as simple as replacing all the dashes using gsub as in R: How to replace . in a string?

I'm thinking it has something to do with the positioning, like telling R to only look after the space. Ideas?

Upvotes: 1

Views: 696

Answers (3)

SymbolixAU
SymbolixAU

Reputation: 26258

You can use library(anytime) to take care of the formatting for you too (which also coerces to POSIX)

library(anytime)

anytime(x)
# [1] "2017-03-17 11:56:20 AEDT"

as.character(anytime(x))
# [1] "2017-03-17 11:56:20"

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193667

Since you're dealing with a date-time object, you can use strptime:

x <- "2017-03-17 11-56-20"
as.character(strptime(x, "%Y-%m-%d %H-%M-%S", tz = ""))
# [1] "2017-03-17 11:56:20"  

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522396

Try matching the following pattern:

(\\d\\d)-(\\d\\d)-(\\d\\d)$

and then replace that with:

\\1:\\2:\\3

This will match your timestamp exclusively, because of the terminal anchor $ at the end of the pattern. Then, we rebuild the timestamp the way you want using colons and the three capture groups.

gsub("(\\d\\d)-(\\d\\d)-(\\d\\d)$", "\\1:\\2:\\3", x)
[1] "2017-03-17 11:56:20"

Upvotes: 3

Related Questions