Separate strings in column

So I have a table formatted like this:
12/30/1899 0:03:43 <- the dd/mm/yyyy, h:mm:ss are all in the same column.

HOw do I separate the strings and sp that I can have dd/mm/yyyy in one column and the hh:mm:ss in another new column so that I can produce cleaner analysis?

I hope everyone is having a great day!

Here is a way to separate the strings and convert them to Date and difftime values so they can be used in calculations.

library(stringr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(hms)
#> 
#> Attaching package: 'hms'
#> The following object is masked from 'package:lubridate':
#> 
#>     hms
DF <- data.frame(DateTime=c("12/30/1899 0:03:43","12/31/1899 11:03:43"))
DF
#>              DateTime
#> 1  12/30/1899 0:03:43
#> 2 12/31/1899 11:03:43
DF2 <- DF |> mutate(Date=mdy(str_extract(DateTime,"../../..")),
                   Time=as_hms(str_extract(DateTime,"(?<= ).+$")))
str(DF2)
#> 'data.frame':    2 obs. of  3 variables:
#>  $ DateTime: chr  "12/30/1899 0:03:43" "12/31/1899 11:03:43"
#>  $ Date    : Date, format: "2018-12-30" "2018-12-31"
#>  $ Time    : 'hms' num  00:03:43 11:03:43
#>   ..- attr(*, "units")= chr "secs"

Created on 2021-12-26 by the reprex package (v2.0.1)

1 Like
the_string <- "12/30/1899 0:03:43"
parts <- strsplit(the_string, " ")
the_date <- parts[[1]][1]
the_time <- parts[[1]][2]
parts
#> [[1]]
#> [1] "12/30/1899" "0:03:43"
the_date
#> [1] "12/30/1899"
the_time
#> [1] "0:03:43"

# better
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

dt_object <- mdy_hms(the_string)
dt_object
#> [1] "1899-12-30 00:03:43 UTC"
year(dt_object)
#> [1] 1899
month(dt_object)
#> [1] 12
wday(dt_object)
#> [1] 7
hour(dt_object)
#> [1] 0
1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.