Home > OS >  New datetime column from date and time
New datetime column from date and time

Time:01-19

still struggling with date and time manipulations despite drawing on some resources and trying some searches.

I have two columns of data as follows:

date_local : chr "11/20/2021" ...

time_local: chr "11:20:30" ...*

The time zone is specified as 'local" in the header, but it more specifically is Eastern Standard Time.

What I am trying to do is create a new datetime_column in the timezone of UTC. I understand these formats are chr (characters), and R wants a format of "POSIXct". Which I think may be the root of the problem. Any help?

CodePudding user response:

I think the lubridate package makes these time zone conversions pretty straigtforward.

library(dplyr)
library(lubridate)

date_local= "11/20/2021" 

time_local="11:20:30"

date_time_EST<- paste(date_local,time_local) %>%  mdy_hms() %>% force_tz("US/Eastern")

date_time_EST
#> [1] "2021-11-20 11:20:30 EST"

date_time_UTC<-date_time_EST %>% with_tz("UTC")

date_time_UTC
#> [1] "2021-11-20 16:20:30 UTC"

so to make this work for your dataframe, you could do

df_new<- df %>%
   mutate(date_time_UTC=paste(date_local,time_local) %>%  mdy_hms() %>% force_tz("US/Eastern") %>% with_tz("UTC"))

Created on 2022-01-15 by the reprex package (v2.0.1)

  •  Tags:  
  • Related