【问题标题】:Cannot calculate Business Days between two dates? Converting dtype('<M8[ns]') to dtype('<M8[D]')?无法计算两个日期之间的工作日?将 dtype('<M8[ns]') 转换为 dtype('<M8[D]')?
【发布时间】:2019-11-24 10:41:03
【问题描述】:

我想计算两个日期之间的工作日(不包括星期日和星期六),一个在数据框列内,另一个是今天的当前日期,但出现错误:

REF8_df['Days_Dif'] = np.busday_count(REF8_df['Session1_Date'], Todays_Date)
File "<__array_function__ internals>", line 6, in busday_count
TypeError: Iterator operand 0 dtype could not be cast from dtype('<M8[ns]') to dtype('<M8[D]') according to the rule 'safe'

我的代码:

df = Main_Database['Session1_Date']
Todays_Date = np.datetime64('today', dtype='datetime64[D]')
df['Session1_Date'] = df['Session1_Date'].values.astype('datetime64[D]')
df['Days_Difference'] = np.busday_count(df['Session1_Date'], Todays_Date)

我很困惑为什么这不起作用?

【问题讨论】:

    标签: python numpy dataframe datetime


    【解决方案1】:

    问题的出现可能是因为数据框和系列仅将类似日期时间的对象保存为 dtype datetime64[ns] 的对象。因此这一行:

    df['Session1_Date'] = df['Session1_Date'].values.astype('datetime64[D]')
    

    不会将转换存储为您想要实现的 .datetime64[D]。以下解决方案有效。

    import datetime
    import pandas as pd
    import numpy as np
    
    # Create a toy data frame
    dates = pd.date_range(datetime.datetime(2019, 4, 5, 0, 
                          0), datetime.datetime(2019, 4, 20, 7, 0),freq='D')
    
    var_1 = np.random.sample(dates.size)
    df = pd.DataFrame(data={'Var_1': var_1, 'Session1_Date': dates})
    df = df[['Session1_Date', 'Var_1']]
    df.head()
    
    # Calculate today's date and convert to 'M8[D]'
    Todays_Date = np.datetime64('today')
    
    # Calculate the business days
    df['Days_Difference'] = np.busday_count(df['Session1_Date'].values.astype('M8[D]'), Todays_Date)
    
    df.head()
    

    输出

    df.head() # Original data frame
    Out[89]: 
      Session1_Date     Var_1
    0    2019-04-05  0.625200
    1    2019-04-06  0.482555
    2    2019-04-07  0.701814
    3    2019-04-08  0.876485
    4    2019-04-09  0.117023
    
    df.head() # With computed business days
    Out[90]: 
      Session1_Date     Var_1  Days_Difference
    0    2019-04-05  0.625200              166
    1    2019-04-06  0.482555              165
    2    2019-04-07  0.701814              165
    3    2019-04-08  0.876485              165
    4    2019-04-09  0.117023              164
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 2020-12-28
      相关资源
      最近更新 更多