如何从日期中减去一天?


Answers:


1288

您可以使用timedelta对象:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

14
如果您不忽略时区,答案将会更复杂
jfs 2014年

另外,您如何将其与特定日期联系起来。看到我的问题:stackoverflow.com/questions/43092508/…–
JohnAndrews

7
在python 3中只是:导入datetime然后d = datetime.today()-datetime.timedelta(days = days_to_subtract)
Alex

它也可以与其他单元一起使用timedelta(minutes=12),例如,我已经使用了它。
Nagev

@legalalien:检查您的import语句:import datetime as DT; DT.datetime.today()是否在Python 2和3上均可使用。它等效于DT.datetime.now()
jfs


62

如果您的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

在一般情况下,day_agoyesterday如果UTC偏移量本地时区中的最后一天发生了变化可能会有所不同。

例如,夏令时/夏令时在美国/洛杉矶时区的Sun 2-Nov-2014的02:00:00 AM结束,因此,如果:

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点而不是上午10点now
  • 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]>

41

只是为了阐明对它有帮助的替代方法和用例:

  • 从当前日期时间减去1天:
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=-1)  # Here, I am adding a negative timedelta
  • 在案例中很有用,如果您想增加5天并从当前日期时间中减去5小时。即从现在算起5天,但少5个小时的日期时间是什么?
from datetime import datetime, timedelta
print datetime.now() + timedelta(days=5, hours=-5)

它可以类似地与其他参数一起使用,例如秒,周等


8

当我想计算上个月的第一天/最后一天或其他相对时间增量等时,我也喜欢使用另一个好函数。

从relativedelta功能dateutil功能(一个强大的扩展到datetime LIB)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, 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

7

存在温和的箭头模块

import arrow
utc = arrow.utcnow()
utc_yesterday = utc.shift(days=-1)
print(utc, '\n', utc_yesterday)

输出:

2017-04-06T11:17:34.431397+00:00 
 2017-04-05T11:17:34.431397+00:00
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.