计算两个日期之间的差异(不包括python中的周末)? [英] Calculate difference between two dates excluding weekends in python?

查看:231
本文介绍了计算两个日期之间的差异(不包括python中的周末)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,该函数返回两个日期(不包括周末和节假日)之间的差额?

I want to create function which return me the difference between two dates excluding weekends and holidays ?

例如:-01/07/2019与08/07之间的差额/ 2019应该给我5天(不包括周末(周末分别为6/7/107和7/07/2019))。

Eg:- Difference between 01/07/2019 and 08/07/2019 should return me 5 days excluding (weekend on 6/7/107 and 7/07/2019).

什么是实现这一目标的最佳方法? ?

What should be best possible way to achieve this ???

推荐答案

尝试使用日期格式将字符串转换为日期,方法是使用 pd.to_datetime()

Try converting string into date using the format of your date using pd.to_datetime()

使用 np.busday_count 以查找除周末外的日期之间的差异

use np.busday_count to find difference between days excluding the weekends

import pandas as pd
import numpy as np

date1 = "01/07/2019"
date2 = "08/07/2019"

date1 = pd.to_datetime(date1,format="%d/%m/%Y").date()
date2 = pd.to_datetime(date2,format="%d/%m/%Y").date()

days = np.busday_count( date1 , date2)
print(days)


5


万一您想提供假期


holidays = pd.to_datetime("04/07/2019",format="%d/%m/%Y").date()
days = np.busday_count( start, end,holidays=[holidays] )
print(days)


4

这篇关于计算两个日期之间的差异(不包括python中的周末)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆