Coder Perfect

How do you take a day off a date?


I have a datetime.datetime object in Python. What’s the greatest method to take a day off?

Asked by defrex

Solution #1

You may use a timedelta object in the following way:

from datetime import datetime, timedelta

d = - timedelta(days=days_to_subtract)

Answered by Steve B.

Solution #2

Subtract datetime.timedelta(days=1)

Answered by S.Lott

Solution #3

If your Python datetime object is timezone aware, you should take the following precautions to avoid issues during DST transitions (or other changes in UTC offset):

from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal

DAY = timedelta(1)
local_tz = get_localzone()   # get local timezone
now = # get timezone-aware datetime object
day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ
naive = now.replace(tzinfo=None) - DAY # same time
yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ

If the UTC offset for the local timezone has changed in the recent day, day ago and yesterday may disagree.

For example, in the America/Los Angeles timezone, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M., therefore if:

import pytz # pip install pytz

local_tz = pytz.timezone('America/Los_Angeles')
now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None)
# 2014-11-02 10:00:00 PST-0800

Then there’s the difference between day ago and yesterday:

The pendulum module takes care of it for you:

>>> import pendulum  # $ pip install pendulum

>>> now = pendulum.create(2014, 11, 2, 10, tz='America/Los_Angeles')
>>> day_ago = now.subtract(hours=24)  # exactly 24 hours ago
>>> yesterday = now.subtract(days=1)  # yesterday at 10 am but it is 25 hours ago

>>> (now - day_ago).in_hours()
>>> (now - yesterday).in_hours()

>>> now
<Pendulum [2014-11-02T10:00:00-08:00]>
>>> day_ago
<Pendulum [2014-11-01T11:00:00-07:00]>
>>> yesterday
<Pendulum [2014-11-01T10:00:00-07:00]>

Answered by jfs

Solution #4

Just to give you an example of an alternative way and a scenario in which it would be useful:

It can also be used with other parameters such as seconds, weeks, and so on.

Answered by Sahil kalra

Solution #5

Another useful function I like to use when I need to compute things like the first/last day of the previous month or other relative timedeltas…

The dateutil function’s relativedelta function (a powerful extension to the datetime lib)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today =
first_day_this_month =, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

Answered by PlagTag

Post is based on