日期时间之间的差异(使用熊猫的工作日数)

时间:2019-05-23 09:44:12

标签: python pandas timedelta

是否有一种(更)方便/有效的方法来计算使用熊猫的日期之间的营业日?

我可以做

len(pd.bdate_range(start='2018-12-03',end='2018-12-14'))-1 # minus one only if end date is a business day

但是对于开始和结束日期之间更长的距离,这似乎效率很低。

关于如何使用BDay偏移对象有一些建议,但是它们似乎都涉及创建日期范围或类似的东西。

我正在考虑在工作日中表示的Timedelta对象。

说我有两个系列,s1s2,包含日期时间。如果熊猫有类似

的含义
s1.dt.subtract(s2,freq='B') 
# giving a new series containing timedeltas where the number of days calculated
# use business days only

会很好。

(numpy有一个busday_count()方法。但是我不想将我的熊猫时间戳转换为numpy,因为这可能会变得凌乱。)

3 个答案:

答案 0 :(得分:1)

我认为np.busday_count是个好主意,也不必转换为numpy数组:

s1 = pd.Series(pd.date_range(start='05/01/2019',end='05/10/2019'))
s2 = pd.Series(pd.date_range(start='05/04/2019',periods=10, freq='5d'))

s = pd.Series([np.busday_count(a, b) for a, b in zip(s1, s2)])
print (s)
0     3
1     5
2     7
3    10
4    14
5    17
6    19
7    23
8    25
9    27
dtype: int64

答案 1 :(得分:0)

from xone import calendar
def business_dates(start, end):
    us_cal = calendar.USTradingCalendar()
    kw = dict(start=start, end=end)
    return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))

In [1]: business_dates(start='2018-12-20', end='2018-12-31')
Out[1]: DatetimeIndex(['2018-12-20', '2018-12-21', '2018-12-24', '2018-12-26',
                       '2018-12-27', '2018-12-28', '2018-12-31'],
                      dtype='datetime64[ns]', freq=None)
来源Get business days between start and end date using pandas

答案 2 :(得分:0)

$prices_and_ids[$article->article_erp_id] = array(
    'price_pvp'       => $article->price_pvp,
    'price_promotion' => $article->price_promotion,
);