【问题标题】:Pandas Get date timestamp which belong to businesshours or BusinessdaysPandas 获取属于营业时间或营业日的日期时间戳
【发布时间】:2020-08-11 20:11:33
【问题描述】:

从给定的列表中找出所有的BusinesshoursBusinessDays。我关注了几个关于 pandas 偏移的文档,但无法弄清楚。 followed stackoverflow as well, here is similar 但没有运气。

>>> d = {'hours': ['2020-02-11 13:44:53', '2020-02-12 13:44:53', '2020-02-11 8:44:53', '2020-02-02 13:44:53']}
>>> df = pd.DataFrame(d)
>>> df
                hours
0  2020-02-11 13:44:53
1  2020-02-12 13:44:53
2   2020-02-11 8:44:53

3  2020-02-02 13:44:53
>>> y = df['hours']
>>> from pandas.tseries.offsets import *
>>> y.apply(pd.Timestamp).asfreq(BDay())
1970-01-01   NaT
Freq: B, Name: hours, dtype: datetime64[ns]
>>> y.apply(pd.Timestamp).asfreq(BusinessHour())
Series([], Freq: BH, Name: hours, dtype: datetime64[ns])

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    我想,你正在寻找类似的东西:

    bh = pd.offsets.BusinessHour()   # avoid not necessary imports
    y.apply(pd.Timestamp).apply(bh.rollforward)
    

    结果是:

    0   2020-02-11 13:44:53
    1   2020-02-12 13:44:53
    2   2020-02-11 09:00:00
    3   2020-02-03 09:00:00
    Name: hours, dtype: datetime64[ns]
    

    所以:

    • 前两个小时没有更改(它们在营业时间内)。
    • 第三次 (2020-02-11 8:44:53) 已提前到 9:00(开始 工作日)。
    • 第四个(2020-02-02 13:44:53 on Sunday)已经提前到下一个 日(星期一)9:00

    或者,如果您只想检查特定日期/小时是否在 营业时间,运行:

    y.apply(pd.Timestamp).apply(bh.onOffset)
    

    结果是:

    0     True
    1     True
    2    False
    3    False
    Name: hours, dtype: bool
    

    表示最后两个日期/小时是营业时间之外。

    【讨论】:

    • 我认为asfreq 用于设置新频率,所以我认为 OP 需要设置 BDay 或 BusinessHour 频率(对我来说不工作)
    • @Valdi_Bo - 完美 :) onOffset 将为我完成这项工作。非常感谢。我在 Python shell 上测试我的代码,所以导入的 *. ;)
    猜你喜欢
    • 2018-11-07
    • 2015-02-25
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    相关资源
    最近更新 更多