Converting Lubridate Period Class Time to Time Stamp Format in R

Viewed 520

My code reads in a .txt file that holds a series of time stamps in one column. I needed to account for daylight savings for the column, so I used the lubridate package to subtract an hour from these time stamps. I'm struggling with converting the period class from lubridate back into a time format of %I:%M%:S %p.

Here is my code.

  # Changing from 24 Hr to 12 Hr Format #
  raw_data_sample$Time <- format(strptime(raw_data_sample$Time, format='%H:%M:%S'), '%I:%M:%S %p')
  
  # Subtracting an Hour for Daylight Savings
  raw_data_sample$Time <- hms(raw_data_sample$Time)
  raw_data_sample$Time <- raw_data_sample$Time - hours(1)

Here is my current output.

c("1H 41M 54S", "1H 42M 4S", "1H 42M 14S", "1H 42M 31S", "1H 42M 41S", "1H 43M 1S")

I'm hoping to get an output like

1:41:54 PM, 1:42:40 PM

Any advice? Thank you!

2 Answers

You can use parse_date_time function to convert your period object to POSIXct then use format to get in your suitable format.

library(lubridate)
raw_data_sample$Time1 <- format(parse_date_time(raw_data_sample$Time, 'HMS'), '%I:%M:%S %p')

For example,

x <- period(c("1H 41M 54S", "1H 42M 4S", "1H 42M 14S", "1H 42M 31S", "1H 42M 41S", "1H 43M 1S"))
format(parse_date_time(x, 'HMS'), '%I:%M:%S %p')
#[1] "01:41:54 AM" "01:42:04 AM" "01:42:14 AM" "01:42:31 AM" "01:42:41 AM" "01:43:01 AM"

If we need to subtract an hour, do this on the original datetime object, and then do the formatting

library(lubridate)
# // convert to Datetime class 
raw_data_sample$Time <- as.POSIXct(raw_data_sample$Time, format = "%H:%M:%S")
 # // subtract 1 hour from the Datetime and use format to change the format
format(raw_data_sample$Time %m-% hours(1), "%I:%M:%S %p")
Related