Subtract hours from time in R
The time objects in R programming language can be declared either using POSIXct class, which offers fast manipulation and storage of such objects. External packages in R also help in working with time and dates and allow both comparison and direct arithmetic operations to be performed upon them.
Method 1 : Using POSIXct object
A date string can be first converted to POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to the standard time zone, UTC. A string type date object can be converted to POSIXct object, using the as.POSIXct(date) method in R. Since, the dates are stored on seconds, the subtraction can be performed by first converting the hours and minutes to the units of seconds too.
1 hour = 1 * 60 * 60 seconds
1 min = 1 * 60 seconds
as.POSIXct ( date , format)
The result is returned as a datetime object with the respective number of hours subtracted belonging to the POSIXct class.
 "Time"  "2021-05-19 08:32:07 UTC"  "Subtracted Time"  "2021-05-19 05:32:07 UTC"
Method 2 : Using lubridate package
Lubridate package in R is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space.
The Sys.time() function in R is used to fetch the current date and time object according to the IST zone. The hours() method in R is used to take an input integer denoting the number of hours. The lubridate package objects allow direct arithmetic over their various components, therefore the number of hours can be directly subtracted from the lubricate time object. A result is also an object belonging to this class.
 "Current time"  "2021-05-19 16:31:37 IST"  "Subtracting 5 hours"  "2021-05-19 11:31:37 IST"
Method 3 : Using strptime() method
strptime method in R is used to directly convert character vectors (of a variety of formats) to POSIXlt format. strptime is faster than the previous approach because strptime() only handles character input.
strptime(date, format, tz = “”)
date – The date in character format
format – The format specifier of the input date
tz – time zone (optional)
strptime() works similar to the POSIXct objects, where all the calculations are done in terms of seconds. Also, the date is returned which is essential in the cases, where the subtraction of certain hours results in the change of date too.
 "Time"  "2021-05-19 00:32:07 IST"  "Subtracted Time"  "2021-05-18 19:32:07 IST"
Please Login to comment...