Reputation: 11
I am working under R and I have a date (format "2018-08-10") and a time (format "10:00:00"). Both are character strings. I need to calculate the beginning time of the event (time - 60 minutes) and pass it to the following format: 20180810T090000Z with year-month-day T hours minutes seconds.
I tried the following:
time <- "10:00:00"
J0 <- "2018-08-10"
library(lubridate)
beginningtime = as.character(hms(time) - minutes(60))
datestart = as.character.POSIXt(as.POSIXct(paste(J0, beginningtime)),
format = "%Y%m%dT%H%M%S")
This gives me datestart
in the following format : "20240301T000000", without taking the time into account.
I guess this relates to the output of as.POSIXct(paste(J0, beginningtime))
, which returns: "2024-03-01 CET", without the beginning time.
Does anyone know how to do this? I'm new to POSIX objects, and I'm at a loss about how to combine all the variants of the as.POSIX
functions in order to get the right output.
Upvotes: 1
Views: 153
Reputation: 19088
With base R using as.POSIXct
and format.Date
beginningtime <- as.POSIXct(paste(J0, time))
format.Date(beginningtime - 60*60, "%Y%m%dT%H%M%SZ")
[1] "20180810T090000Z"
Note that beginningtime is left as a Date object. IMO there seems no good reason to store the date as character since the format change happens afterwards anyways.
Upvotes: 3
Reputation: 5620
Using lubridate
you can paste
your J0
and time
objects, and then use ymd_hms
to convert it from character to date. Then, you can subtract 60 minutes and set your desired output format (with stamp
) to the result.
library(lubridate)
# Create desired output format
datestamp <- stamp("2018-08-10T10:00:00Z")
# Paste ymd and hms, and convert to date
date <- ymd_hms(paste(J0, time))
# Subtract 60 minutes
date <- date - minutes(60)
# Apply desired format
datestamp(date)
[1] "2018-08-10T09:00:00Z"
Upvotes: 2