How to Add or subtract time span to a datetime in R ?
Last Updated :
30 May, 2021
The time objects in R 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. In this article, we are going to see how to add and subtract a time span to a DateTime in R Programming.
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 them as.POSIXct(date) method in R. Since, the dates are stored in terms of seconds, the subtraction, as well as addition, can be performed by first converting the hours and minutes to the units of seconds too. Mathematical operators can directly be used to add various time components to the date object, which belongs to the POSIXct class.
1 hour = 1 * 60 * 60 seconds
1 min = 1 * 60 seconds
Syntax: as.POSIXct ( date , format)
Arguments :
date - The string date object
format - The format specifier of the date
Code:
R
# declaring a datetime object
time1 <- as.POSIXct("2021-05-08 08:32:07",
format = "%Y-%m-%d %H:%M:%S")
print ("Original DateTime")
print (time1)
# adding 20 mins to datetime
mins <- 20 * 60
print ("Adding 20 mins to DateTime")
print (time1 + mins)
# converting 3 hours to seconds
hrs <- 3 * 60 * 60
print ("Subtracting 3 hours from DateTime")
# subtracting 3 hours from the
# date time object
print (time1 - hrs)
Output:
[1] "Original DateTime"
[1] "2021-05-08 08:32:07 UTC"
[1] "Adding 20 mins to DateTime"
[1] "2021-05-08 08:52:07 UTC"
[1] "Subtracting 3 hours from DateTime"
[1] "2021-05-08 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 by the following command :
install.packages("lubridate")
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 of an integer denoting the number of hours. The "lubridate" package objects allow direct arithmetic over its various components, therefore the number of hours can be directly subtracted from the lubridate time object. A result is also an object belonging to this class.
Code:
R
# getting required libraries
library(lubridate)
# getting current time
time <- Sys.time()
print("Current time")
print (time)
# subtracting hours
hrs <- hours(5)
print ("Subtracting 5 hours")
mod_time <- time - hrs
print (mod_time)
secs <- seconds(17)
print ("Adding 17 seconds")
mod_time <- time + secs
print (mod_time)
Output
[1] "Current time"
[1] "2021-05-22 03:27:02 IST"
[1] "Subtracting 5 hours"
[1] "2021-05-21 22:27:02 IST"
[1] "Adding 17 seconds"
[1] "2021-05-22 03:27:19 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.
Syntax: strptime(date, format, tz = "")
Arguments :
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.
Code:
R
# declaring a time object
time1 <- strptime("2021-07-07 00:32:07",
format = "%Y-%m-%d %H:%M:%S")
print ("Time")
print (time1)
# converting 5 hours to seconds
hrs <- 5 * 60 * 60
print ("Subtracting 5 hours")
print (time1 - hrs)
# adding 48 seconds and 24 mins
mins <- 24 * 60
secs <- 48 * 60 * 60
print ("Modified Time")
print ((time1 + mins) - secs)
Output:
[1] "Time"
[1] "2021-07-07 00:32:07 UTC"
[1] "Subtracting 5 hours"
[1] "2021-07-06 19:32:07 UTC"
[1] "Modified Time"
[1] "2021-07-05 00:56:07 UTC"
Explanation: The subtraction of 5 hours, leads to the return of the previous date. In the second scenario, the respective number of minutes and seconds are computed.
Similar Reads
How to separate date and time in R ? In this article, we are going to separate date and time in R Programming Language.  Date-time is in the format of date and time (YYYY/MM/DD HH:MM:SS- year/month/day Hours:Minute:Seconds). Extracting date from timestamp: We are going to extract date by using as.Date() function. Syntax:  as.Date(data
2 min read
How to add time onto a DateTime object in Python In Python, adding time (such as hours, minutes, seconds, or days) to a datetime object is commonly done using the timedelta class from the datetime module. This allows precise manipulation of date and time values, including performing arithmetic operations on datetime objects. It's key features incl
3 min read
How to Add or Subtract Dates in Excel New to Excel and seeking a way to add or subtract dates, then this guide on how to add or subtract dates in Excel will expalin you the right way to manage project timelines, schedules, or due dates. Weâll break down simple steps to add or subtract dates using easy formulas and time-saving tips.How t
5 min read
How to Add and Subtract Days to and from Date in R? Managing dates and times is a crucial aspect of data analysis, and R provides robust facilities for dealing with date objects. In this post, we will look at how to add and remove days from a date in R. Whether you're dealing with time series data, need to compute future dates, or want to browse thro
4 min read
How to add and subtract days using DateTime in Python? Pythonâs built-in datetime module provides powerful tools to work with dates and times. One of its common tasks is manipulating dates by adding or subtracting days, hours, minutes and more. It's key classes in the datetime module.NameDescriptiondateIt shows the date according to the Georgian calenda
3 min read
How to add and subtract days using DateTime in Python? Pythonâs built-in datetime module provides powerful tools to work with dates and times. One of its common tasks is manipulating dates by adding or subtracting days, hours, minutes and more. It's key classes in the datetime module.NameDescriptiondateIt shows the date according to the Georgian calenda
3 min read