【问题标题】:Subtract datetime now from a dataframe column without Saturday and Sunday现在从没有周六和周日的数据框列中减去日期时间
【发布时间】:2021-07-01 05:26:00
【问题描述】:

目前,我的脚本正在用我在名为“Creation”的 Dataframe 列中的时间减去我当前的时间,生成一个包含不同天数的新列。我用这段代码得到了不同的天数:

df['Creation']= pandas.to_datetime(df["Creation"],dayfirst="True")

#Generates new column with the days.
df['Difference'] = df.to_datetime('now') - df['Creation']

我现在想要的是让它给我像他给我一样的日子,但不计算周六和周日。我该怎么做?

【问题讨论】:

  • 所以df['Difference'] 的计算应该排除周六和周日,对吗?
  • 是的,给我没有周六周日的日子

标签: python dataframe datetime timedelta


【解决方案1】:

你可以使用numpybusday_count,例如:

import pandas as pd
import numpy as np

# some dummy data
df = pd.DataFrame({'Creation': ['2021-03-29', '2021-03-30']})

# make sure we have datetime
df['Creation'] = pd.to_datetime(df['Creation'])

# set now to a fixed date
now = pd.Timestamp('2021-04-05')

# difference in business days, excluding weekends
# need to cast to datetime64[D] dtype so that np.busday_count works
df['busday_diff'] = np.busday_count(df['Creation'].values.astype('datetime64[D]'),
                                    np.repeat(now, df['Creation'].size).astype('datetime64[D]'))

df['busday_diff'] # since I didn't define holidays, potential Easter holiday is excluded:
0    5
1    4
Name: busday_diff, dtype: int64

如果您需要输出为 dtype timedelta,您可以通过以下方式轻松转换为该类型

df['busday_diff'] = pd.to_timedelta(df['busday_diff'], unit='d')

df['busday_diff']
0   5 days
1   4 days
Name: busday_diff, dtype: timedelta64[ns]

注意:np.busday_count 还允许您设置自定义星期掩码(排除周六和周日以外的日期)或假期列表。请参阅我在顶部链接的文档。

相关: Calculate difference between two dates excluding weekends in python?, how to use (np.busday_count) with pandas.core.series.Series

【讨论】:

  • 那行得通,有没有办法不将 dtype 转换为 int64 而是转换为 timedelta(64)?
  • @Ricardoke 是的,已编辑。我认为最简单的方法是使用pd.to_timedelta 转换为 timedelta。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多