When you have a date, it's common to need to apply math to that date. For example maybe you want to move to tomorrow or to yesterday.
Datetimes support math operations, such as adding or subtracting to them, but when time is involved, it's not easy to get the exact number of seconds you need to add or subtract to move to the next or previous day.
For this reason, this recipe will show off an easy way to move to the next or previous day from any given date.
For this recipe, here are the steps:
- The
shiftdate
function will allow us to move to a date by any number of days:
import datetime def shiftdate(d, days): return ( d.replace(hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(days=days) )
- Using it is as simple as just providing the days you want to add or remove:
>>> now = datetime.datetime.utcnow()
>>> now
datetime.datetime(2018, 3, 21, 21, 55, 5, 699400)
>>> shiftdate...