編寫一個Python函式來計算從起始日期到結束日期之間的總工作日數。
假設你有一系列日期date_range,並且總工作日的結果是:
Dates are: DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07', '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-13', '2020-01-14', '2020-01-15', '2020-01-16', '2020-01-17', '2020-01-20', '2020-01-21', '2020-01-22', '2020-01-23', '2020-01-24', '2020-01-27', '2020-01-28', '2020-01-29', '2020-01-30', '2020-01-31'], dtype='datetime64[ns]', freq='B') Total number of days: 23
方案1
定義一個名為business_days()的函式
設定pd.bdate_range()函式的起始值為’2020-01-01’,結束值為’2020-02-02’,並將其儲存為dates。
dates = pd.bdate_range('2020-01-01','2020-02-02')使用len(dates)計算天數。
len(dates)
示例
讓我們檢查以下程式碼以更好地理解:
import pandas as pd
def business_days():
dates = pd.bdate_range('2020-01-01','2020-02-02')
print("Total number of days:",len(dates))
business_days()輸出
Total number of days: 23
方案2
定義一個函式
設定pd.bdate_range()函式的起始值為’2020-01-01’,結束值為’2020-02-02’,並將其儲存為dates。
dates = pd.bdate_range('2020-01-01','2020-02-02')將count設定為0,並建立一個for迴圈來訪問dates中的所有值,並將count值自身加1。
count = 0 for i in dates: count = count + 1
最後,列印count。
示例
import pandas as pd
def business_days():
dates = pd.bdate_range('2020-01-01','2020-02-02')
count = 0
for i in dates:
count = count + 1
print("Total number of days:",count)
business_days()輸出
Total number of days: 23
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP