熊猫 - 在日期和当前时间之间获得营业时间

时间:2018-05-29 00:59:04

标签: python pandas datetime time

我知道这是一个经常被问到的问题,但我只找到了一个允许我使用businesstimedelta库来使用本地日历和假期的解决方案。

我目前在两个日期列之间获取数据的代码有效

df如下(使用pd.datetime.now()创建日期列:

Index   Created Date        Updated Date        Diff Hrs    Current Date
10086   2016-11-04 16:00:00 2016-11-11 11:38:00 35.633333   2018-05-29 10:09:11.291391
10087   2016-11-04 16:03:00 2016-11-29 12:54:00 132.850000  2018-05-29 10:09:11.291391
10088   2016-11-04 16:05:00 2016-11-16 08:05:00 56.916667   2018-05-29 10:09:11.291391
10089   2016-11-04 16:17:00 2016-11-08 11:37:00 11.333333   2018-05-29 10:09:11.291391
10090   2016-11-04 16:20:00 2016-11-16 09:58:00 57.633333   2018-05-29 10:09:11.291391
10091   2016-11-04 16:32:00 2016-11-08 11:10:00 10.633333   2018-05-29 10:09:11.291391

Created DateUpdated Date之间产生差异的工作代码如下:

import datetime
import pytz
import businesstimedelta
import holidays as pyholidays

workday = businesstimedelta.WorkDayRule(
    start_time=datetime.time(9),
    end_time=datetime.time(17),
    working_days=[0, 1, 2, 3, 4])


vic_holidays = pyholidays.AU(prov='VIC')
holidays = businesstimedelta.HolidayRule(vic_holidays)
businesshrs = businesstimedelta.Rules([workday, holidays])

def BusHrs(start, end):
    return businesshrs.difference(start,end).hours+float(businesshrs.difference(start,end).seconds)/float(3600)

df['Diff Hrs'] = df.apply(lambda row: BusHrs(row['Created Date'], row['Updated Date']), axis=1)   

运行需要一段时间但是有效 - 但是尝试根据当前时间和更新时间之间的差异来创建新列。 df['Time Since Last Update'] = df.apply(lambda row: BusHrs(row['Current Date'], row['Updated Date']), axis=1)失败/需要永远,我不知道为什么。

非常感谢有关计算Time Since Last Update的任何帮助。

1 个答案:

答案 0 :(得分:1)

您需要在row['Current Date']中反转row['Updated Date']df['Time Since Last Update'],然后使用

df['Time Since Last Update'] = df.apply(lambda row: BusHrs(row['Updated Date'], row['Current Date']), axis=1)

它应该有用。我假设start不能在end函数中businesshrs.difference之后。 此外,如果您想加快代码的速度,请执行以下操作:

def BusHrs(start, end):
    diff_businesshrs = businesshrs.difference(start,end)
    # like this you calculate only once businesshrs.difference(start,end)
    return diff_businesshrs.hours+float(diff_businesshrs.seconds)/float(3600)
编辑我认为我发现了一种更快捷的方法。因为从2016年到现在的事物之间的营业时间很长,每行计算一次,我认为通过计算两个成功更新日期之间的小时数,然后sum超过这些部分计算直到当前日期,你可以做得更快。您需要两个临时列,一个具有转移的更新日期,另一个具有部分营业时间

df = df.sort_values('Updated Date').reset_index()
df['Shift Date'] = df['Updated Date'].shift(-1).fillna(pd.datetime.now())
df['BsnHrs Partial'] = df.apply(lambda row: BusHrs(row['Updated Date'], row['Shift Date']), axis=1)
df['Time Since Last Update'] = df.apply(lambda row: df['BsnHrs Partial'][row.name:].sum(), axis=1)
df = df.drop(['Shift Date','BsnHrs Partial'],1).set_index('index') # drop and reindex
df = df.sort_index() #if you want to go back to the original order
相关问题