如何从日期中减去一天?

我有一个Python datetime.datetime对象。 减去一天的最佳方式是什么?


您可以使用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_agoyesterday可能会有所不同。

例如,夏令时/夏令时在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_agoyesterday不同:

  • 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]>
    
    链接地址: http://www.djcxy.com/p/18479.html

    上一篇: How to subtract a day from a date?

    下一篇: Get Last Day of the Month in Python