如何从两个数据时间中提取工作时间

时间:2017-07-05 16:41:37

标签: python pandas

我有一个带有员工开始时间和结束时间的pandas数据框。我想知道一名员工在特定班次工作了多少小时(Shift1:上午8:00至下午2:00;班次2:2 pm-10pm,班次3:10 pm-8am)。感谢您的帮助。

         Start        End
0 2015-01-01 18:44:00 2015-01-02 07:31:00
1 2015-01-01 06:38:00 2015-01-01 19:57:00
2 2015-01-01 06:34:00 2015-01-01 19:13:00
3 2015-01-01 18:48:00 2015-01-02 07:15:00
4 2015-01-01 06:50:00 2015-01-01 20:02:00

1 个答案:

答案 0 :(得分:0)

请注意,我的答案还不是很完美。首先,我创建了有问题的示例数据集。

import pandas as pd

df = pd.DataFrame([
    ['2015-01-01 18:44:00', '2015-01-02 07:31:00'], 
    ['2015-01-01 06:38:00', '2015-01-01 19:57:00'],
    ['2015-01-01 06:34:00', '2015-01-01 19:13:00'],
    ['2015-01-01 18:48:00', '2015-01-02 07:15:00'],
    ['2015-01-01 06:50:00', '2015-01-01 20:02:00']
], columns=['start', 'stop'])

df.start = pd.to_datetime(df.start)
df.stop = pd.to_datetime(df.stop)

然后在给定的每个班次间隔之间找出工作时间

from datetime import datetime, timedelta


def find_interval(r):
    """
    r: row of dataframe, with 'start' and 'stop' column
    """
    t_start = r['start']
    t_stop = r['stop']
    t = t_start
    s1_start = datetime(t.date().year, t.date().month, t.date().day, 8)
    s1_stop = datetime(t.date().year, t.date().month, t.date().day, 14)
    s2_start = datetime(t.date().year, t.date().month, t.date().day, 14)
    s2_stop = datetime(t.date().year, t.date().month, t.date().day, 22)
    s3_start = datetime(t.date().year, t.date().month, t.date().day, 22)
    s3_stop = datetime(t.date().year, t.date().month, t.date().day + 1, 8)

    shift_hours = []
    for (s_start, s_stop) in [(s1_start, s1_stop), (s2_start, s2_stop), (s3_start, s3_stop)]:
        if t_stop < s_start:
            shift_hours.append(timedelta(seconds=0))
        elif t_stop > s_start and t_stop < s_stop:
            shift_hours.append(t_stop - s_start)
        elif t_start < s_stop and t_stop > s_stop:
            shift_hours.append(s_stop - t_start)
        else:
            shift_hours.append(timedelta(seconds=0))
    return shift_hours

连接回来

df_shift = pd.DataFrame([find_interval(r) for _, r in df.iterrows()])
df_out = pd.concat((df, df_shift), axis=1) # output