How to subtract a day from a date?
I have a Python datetime.datetime
object. What is the best way to subtract one day?
您可以使用timedelta对象:
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract)
减去datetime.timedelta(days=1)
If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons):
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
In general, day_ago
and yesterday
may differ if UTC offset for the local timezone has changed in the last day.
For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 AM in America/Los_Angeles timezone therefore if:
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
then day_ago
and yesterday
differ:
day_ago
is exactly 24 hours ago (relative to now
) but at 11 am, not at 10 am as now
yesterday
is yesterday at 10 am but it is 25 hours ago (relative to now
), not 24 hours. pendulum
module handles it automatically:
>>> 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/18480.html
上一篇: 为什么1/1/1970是“纪元时间”?
下一篇: 如何从日期中减去一天?