如何從日期減去一天?

我有一個Python datetime.datetime對象。 減去一天的最佳方法是什麼? html


#1樓

只是爲了詳細說明一個有用的替代方法和用例: python

  • 從當前日期時間減去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)

它能夠相似地與其餘參數一塊兒使用,例如秒,周等 函數


#2樓

若是您的Python日期時間對象是時區感知的,那麼您應該當心避免DST轉換周圍的錯誤(或因爲其餘緣由而改變UTC偏移): this

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可能會有所不一樣。 spa

例如,夏令時/夏令時將於2014年11月2日上午02:00:00在America / Los_Angeles時區結束,所以: code

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不一樣: orm

  • day_ago剛好是24小時前(相對於now )可是在上午11點,而不是now上午10點
  • yesterday是昨天上午10點,可是是25小時前(相對於now ),而不是24小時。

pendulum模塊自動處理: htm

>>> 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]>

#3樓

另外,當我想要計算上個月的第一天/最後一天或其餘相對時間等時,我喜歡使用另外一個不錯的功能...... 對象

來自dateutil函數的relativedelta函數(對datetime lib的強大擴展) ip

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

#4樓

Genial arrow模塊存在

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

#5樓

您可使用timedelta對象:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
相關文章
相關標籤/搜索