R Time Differences
difftime() measures the gap between two moments in time. A moment holds a date and a clock time in one value.
Build a moment in time
The text holds the date first and the clock time after it. The tz argument fixes the zone as UTC, and the moment prints with that zone.
t1 <- as.POSIXct("2024-01-01 10:00:00", tz = "UTC")
print(t1)Measure a gap in hours
The second moment is two and a half hours after the first. difftime() prints the gap in the unit the units argument names.
t1 <- as.POSIXct("2024-01-01 10:00:00", tz = "UTC")
t2 <- as.POSIXct("2024-01-01 12:30:00", tz = "UTC")
print(difftime(t2, t1, units = "hours"))Measure a gap in other units
Two moments two days apart give a gap of 2 in days. The same gap gives 2880 in minutes.
t1 <- as.POSIXct("2024-01-01 10:00:00", tz = "UTC")
t2 <- as.POSIXct("2024-01-03 10:00:00", tz = "UTC")
print(difftime(t2, t1, units = "days"))
print(difftime(t2, t1, units = "mins"))Break a moment into parts
as.POSIXlt() stores the parts of a moment under names. Adding 1900 to the year part and 1 to the month part gives the plain calendar values.
t1 <- as.POSIXct("2024-01-01 10:00:00", tz = "UTC")
parts <- as.POSIXlt(t1)
print(parts$year + 1900)
print(parts$mon + 1)
print(parts$mday)
print(parts$wday)
print(parts$hour)Example
start <- as.POSIXct("2024-06-15 09:15:00", tz = "UTC")
end <- as.POSIXct("2024-06-15 11:45:00", tz = "UTC")
print(difftime(end, start, units = "hours"))
parts <- as.POSIXlt(start)
print(parts$hour)
print(parts$mday)
print(parts$wday)Key points
- as.POSIXct() builds a moment from text that holds a date and a clock time.
- The tz argument names the time zone of the moment.
- difftime() returns the gap between two moments.
- The units argument chooses the unit the gap is measured in, such as hours or days.
- as.POSIXlt() breaks a moment into named parts such as year, month, day and hour.
- The year part counts the years since 1900, so the full year is the part plus 1900.
- The month part counts from 0, so the month number is the part plus 1.
In this example the gap between the start and the end prints in hours. The parts of the start then give its hour, its day of the month and its weekday number.
Note
The weekday part counts from 0, and Sunday is 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does difftime(t2, t1, units = "hours") print when t2 is 90 minutes after t1?