0

I have a dataframe which has a column (expires) with unix time codes. I want to convert these to TWO separate columns, one for time (expires_time) and one for date (expires_date). I've started with a simple piece of code from this post: Convert UNIX time string to date in R

What I have so far is:

df$expires_converted <- as.POSIXct(df$expires, origin = "1970-01-01")

This produces a new column called expires_converted which gives me both the time and date in the following format:

2021-08-03 17:50:00

Is there a way to convert the unix code into two separate columns as per my description above? I realise I could simply split the new column into two new columns using the white space to separate them, but I wonder if there is a simpler way to do this?

Japes
  • 209
  • 1
  • 10
  • Does this answer your question? [Extract date and time from datetime field in R](https://stackoverflow.com/questions/63677684/extract-date-and-time-from-datetime-field-in-r) – Limey Jul 06 '21 at 16:02
  • Not quite - I was hoping there was a way to amend the code I'm using (see my post) rather than adding another step. I've already got a solution using "separate" to split the column at the whitespace. I just wondered if there was a way to do this in one go! – Japes Jul 06 '21 at 16:35

1 Answers1

1

R doesn't have a built-in Time class, so your solution is going to depend on how you want to store your times: as characters or as a package-dependent time class.

Also, if by "in one go" you mean "in one statement", then probably not because you want to store the data in two separate columns, which will most likely mean two different assignments. But you can get close:

library(lubridate)
library(hms)
library(tibble)

tibble(
  d=now(), 
  datePart=as_date(d),
  timePart=as_hms(d)
)
# A tibble: 1 x 3
  d                   datePart   timePart       
  <dttm>              <date>     <time>         
1 2021-07-06 17:53:07 2021-07-06 17:53:07.114918

Note that there's no need to embed the conversions in a tibble. I've done it this way simply to get a concise confirmation of the class of each part of the derivation.

Limey
  • 10,234
  • 2
  • 12
  • 32