我有一個Python datetime.datetime
對象。 減去一天的最佳方法是什麼? html
只是爲了詳細說明一個有用的替代方法和用例: python
from datetime import datetime, timedelta print datetime.now() + timedelta(days=-1) # Here, I am adding a negative timedelta
from datetime import datetime, timedelta print datetime.now() + timedelta(days=5, hours=-5)
它能夠相似地與其餘參數一塊兒使用,例如秒,周等 函數
若是您的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_ago
和yesterday
可能會有所不一樣。 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_ago
和yesterday
不一樣: 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]>
另外,當我想要計算上個月的第一天/最後一天或其餘相對時間等時,我喜歡使用另外一個不錯的功能...... 對象
來自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
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
您可使用timedelta對象:
from datetime import datetime, timedelta d = datetime.today() - timedelta(days=days_to_subtract)