Adding or subtracting a time span to a datetime
A common use of time spans is to add or subtract them from a moment in time. For, example to calculate the time one day in the future from mar_11
(from the previous exercises), you could do either of:
mar_11 + days(1)
mar_11 + ddays(1)
Try them in the console, you get different results! But which one is the right one? It depends on your intent. If you want to account for the fact that time units, in this case days, have different lengths (i.e. due to daylight savings), you want a period days()
. If you want the time 86400 seconds in the future you use a duration ddays()
.
In this exercise you'll add and subtract timespans from dates and datetimes.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
- It's Monday Aug 27th 2018 at 2pm and you want to remind yourself this time next week to send an email. Add a period of one week to
mon_2pm
. - It's Tuesday Aug 28th 2018 at 9am and you are starting some code that usually takes about 81 hours to run. When will it finish? Add a duration of 81 hours to
tue_9am
. - What were you doing five years ago? Subtract a period of 5 years from
today()
. - Subtract a duration of 5 years from
today()
. Will this give a different date?
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add a period of one week to mon_2pm
mon_2pm <- dmy_hm("27 Aug 2018 14:00")
mon_2pm + ___
# Add a duration of 81 hours to tue_9am
tue_9am <- dmy_hm("28 Aug 2018 9:00")
tue_9am + ___
# Subtract a period of five years from today()
today() - ___
# Subtract a duration of five years from today()
today() - ___