Skip to main content
 首页 » 编程设计

python之Pandas之获取日期和当前时间之间的营业时间

2024年12月31日12mayingbao

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

我当前用于在两个日期列之间获取数据的代码有效。

df如下(created date column made with 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 Date 和 Updated 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)    

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

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

请您参考如下方法:

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

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

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

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