Menkot
Menkot

Reputation: 734

How to cut a datetime and remain the time part only

I have data like below:

2018-04-01 00:12:45.823 
2018-04-01 00:12:49.897 
2018-04-01 00:12:56.207

How to cut them only remain:

00:12:45.823
00:12:49.897
00:12:56.207

Upvotes: 4

Views: 230

Answers (4)

Yuriy Barvinchenko
Yuriy Barvinchenko

Reputation: 1595

library(rebus)
library(stringr)
datetimes <- c('2018-04-01 00:12:45.823', 
'2018-04-01 00:12:49.897', 
'2018-04-01 00:12:56.207')
dgt2 <- DGT %R% DGT
str_extract(datetimes, dgt2 %R% ':' %R% dgt2 %R% ':' %R% dgt2 %R% DOT %R% dgt2 %R% DGT)

May be more readable. dgt2 is 2 digits to make expression shorter.

[1] "00:12:45.823" "00:12:49.897" "00:12:56.207"

The same result gives this:

str_extract(datetimes, digit(2,2) %R% ':' %R% digit(2,2) %R% ':' %R% digit(2,2) %R% DOT %R% digit(3,3))

Upvotes: 2

string a = DateTime.UtcNow.ToLongTimeString(); Replace DateTime.UtcNow to your dateTime and get easily time string.

Upvotes: 0

akrun
akrun

Reputation: 887128

We can use sub to match characters until one or more spaces (\\s+) and replace with blank ("")

sub("^[^ ]+\\s+", "", df1$col)
#[1] "00:12:45.823" "00:12:49.897" "00:12:56.207"

Or convert to POSIXct and then format (here, there could be slight changes in accuracy of the decimals)

format(as.POSIXct(df1$col), "%H:%M:%OS3")
#[1] "00:12:45.822" "00:12:49.897" "00:12:56.207"

Or with separate from tidyverse

library(tidyverse)
df1 %>% 
   separate(col, into = c('col1', 'col2'), sep=" ") %>% 
   select(col2)

data

str1 <- c("2018-04-01 00:12:45.823", "2018-04-01 00:12:49.897", 
           "2018-04-01 00:12:56.207")
df1 <- data.frame(col = str1, stringsAsFactors = FALSE)

Upvotes: 4

NelsonGon
NelsonGon

Reputation: 13319

We can also use and convert back to time:

mytime<-"2018-04-01 00:12:45.823"
strsplit(mytime," ")[[1]][2]
#[1] "00:12:45.823"

Well, reading this data with read.table breaks it up "nicely":

mytime<-read.table(text="2018-04-01 00:12:45.823 
2018-04-01 00:12:49.897 
                   2018-04-01 00:12:56.207",header=F)
      V1           V2
1 2018-04-01 00:12:45.823
2 2018-04-01 00:12:49.897
3 2018-04-01 00:12:56.207

Upvotes: 6

Related Questions