Python 中最近的前一个工作日 [英] Most recent previous business day in Python

查看:33
本文介绍了Python 中最近的前一个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从当前日期减去工作日.

I need to subtract business days from the current date.

我目前有一些代码需要始终在最近的工作日运行.所以如果我们是周一到周五,那可能是今天,但如果是周六或周日,那么我需要将它设置回周末之前的周五.我目前有一些非常笨拙的代码来执行此操作:

I currently have some code which needs always to be running on the most recent business day. So that may be today if we're Monday thru Friday, but if it's Saturday or Sunday then I need to set it back to the Friday before the weekend. I currently have some pretty clunky code to do this:

 lastBusDay = datetime.datetime.today()
 if datetime.date.weekday(lastBusDay) == 5:      #if it's Saturday
     lastBusDay = lastBusDay - datetime.timedelta(days = 1) #then make it Friday
 elif datetime.date.weekday(lastBusDay) == 6:      #if it's Sunday
     lastBusDay = lastBusDay - datetime.timedelta(days = 2); #then make it Friday

有没有更好的办法?

例如,我可以告诉 timedelta 在工作日而不是日历日工作吗?

Can I tell timedelta to work in weekdays rather than calendar days for example?

推荐答案

使用 Pandas!

import datetime
# BDay is business day, not birthday...
from pandas.tseries.offsets import BDay

today = datetime.datetime.today()
print(today - BDay(4))

由于今天是 9 月 26 日星期四,因此您将得到以下输出:

Since today is Thursday, Sept 26, that will give you an output of:

datetime.datetime(2013, 9, 20, 14, 8, 4, 89761)

这篇关于Python 中最近的前一个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆