我有一个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
在一般情况下,day_ago
以及yesterday
如果UTC本地时区偏移在最后一天发生了变化可能会有所不同.
例如,夏令时/夏令时将于2014年11月2日上午02:00:00在America/Los_Angeles时区结束,因此:
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
不同:
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>>> day_ago >>> yesterday
只是为了详细说明一个有用的替代方法和用例:
从当前日期时间减去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)
它可以类似地与其他参数一起使用,例如秒,周等
另外,当我想要计算上个月的第一天/最后一天或其他相对时间等时,我喜欢使用另一个不错的功能......
来自dateutil函数的relativedelta函数(对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
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