user3022875
user3022875

Reputation: 9018

How to create a time from a POSIXct

I have some dates in POSIXct format

head(data$Dates,3)  

[1] "2015-01-02 16:34:01 GMT" "2015-01-28 16:33:03 GMT" "2015-01-16 20:55:35 GMT"

And I would like to create a column that is the DATE of each element with the time of 21:00:00 GMT and then subtract this new date from the original.

So from that vector of dates I want to create a vector of POSIXct that looks like

  "2015-01-02 21:00:00 GMT" "2015-01-28 21:00:00 GMT" "2015-01-16 21:00:00 GMT"

Then I want to subtract this new vector from the first one.

How do I create the vector that looks like:

 "2015-01-02 21:00:00 GMT" "2015-01-28 21:00:00 GMT" "2015-01-16 21:00:00 GMT"

Thank you.

Upvotes: 0

Views: 70

Answers (2)

JasonAizkalns
JasonAizkalns

Reputation: 20463

It's not entirely clear if this is the type of result you are going after, but this should get you started.

dates <- as.POSIXct(c("2015-01-02 16:34:01 GMT", 
                      "2015-01-28 16:33:03 GMT", 
                      "2015-01-16 20:55:35 GMT"))
library(lubridate)

orig_dates  <- ymd_hms(dates)
trunc_dates <- floor_date(orig_dates, "day")
trunc_dates_21st_hour <- trunc_dates + ehours(21)

orig_dates - trunc_dates_21st_hour
# Time differences in mins
# [1] -265.983333 -266.950000   -4.416667

Upvotes: 0

orange1
orange1

Reputation: 2939

I recommend using the lubridate package. It will enable you to subtract dates from each other. Do you want to set the time to be the same thing for each one as an intermediary step in date subtraction? Slicing the first part of the timestamp to just get the date, using something like:

clean_date <- function(date){
date = substr(date, 1, 10)
return(date)
}

df$Date <- clean_date(df$Date)

and then just converting that to a lubridate date object, using

df$Date <- ymd(date)

should allow you to find the difference between the two dates easily, and will create a difftime object that will give you the the differenced between the two dates in your chosen unit.

Upvotes: 0

Related Questions