您可以使用timedelta对象:
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract)
减去datetime.timedelta(days=1)
如果您的 Python 日期时间对象可识别时区,则应注意避免 DST 转换周围的错误(或由于其他原因导致 UTC 偏移量发生变化):
from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal
DAY = timedelta(1)
local_tz = get_localzone() # get local timezone
now = datetime.now(local_tz) # 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
通常,如果本地时区的 UTC 偏移在最后一天已更改,则day_ago
和yesterday
可能会有所不同。
例如,夏令时 / 夏令时在美国 / 洛杉矶时区的 2014 年 11 月 2 日(星期日)结束于 02:00:00,因此,如果:
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
那么day_ago
和yesterday
不同:
day_ago
恰好是 24 小时前(相对于now
),但在上午 11 点而不是now
上午 10 点yesterday
是昨天上午 10 点,但是是 25 小时前(相对于now
),而不是 24 小时。 pendulum
模块自动处理它:
>>> 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()
24
>>> (now - yesterday).in_hours()
25
>>> 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]>