![](/img/trans.png)
[英]How to get the number of values from a database field for the last 10 days
[英]how to get last 10 business days if
我想根據過去 10 個工作日創建 dataframe。 它還應該檢查這一天是否是公共假期。 我有一個公共假期的清單。
公共假期列表如下:
假期 |
---|
2021-01-26 |
2021-03-11 |
2021-03-29 |
2021-04-02 |
2021-04-14 |
2021-04-21 |
2021-05-13 |
2021-07-21 |
2021-08-19 |
2021-09-10 |
2021-10-15 |
2021-11-04 |
2021-11-05 |
2021-11-19 |
周末周六和周日。
所以我今天運行代碼,也就是 2021 年 2 月 27 日星期六,而不是 output 應該是這樣的
工作日 |
---|
2021-02-15 |
2021-02-16 |
2021-02-17 |
2021-02-18 |
2021-02-19 |
2021-02-22 |
2021-02-23 |
2021-02-24 |
2021-02-25 |
2021-02-26 |
我沒有測試這段代碼,但它應該可以工作
import datetime
today = datetime.datetime.now()
business_days = []
#holidays = [ your list of holidays in here ]
i = 0
while True:
temp_date = today - datetime.timedelta(i)
if temp_date.weekday() in (0,1,2,3,4) and temp_date not in holidays:
if len(business_days)<10:
business_days.append(temp_date)
else:
break
i += 1
print(business days)
注意:如果您需要以特定格式顯示日期,則需要格式化日期
@pi_pascal 的替代方案:
hols = ["2021-01-26", "2021-03-11", "2021-03-29", "2021-04-02",
"2021-04-14", "2021-04-21", "2021-05-13", "2021-07-21",
"2021-08-19", "2021-09-10", "2021-10-15", "2021-11-04",
"2021-11-05", "2021-11-19"]
hols = pd.to_datetime(hols)
bdays = pd.bdate_range(end=pd.Timestamp.today(), periods=60, freq="1D", closed="left")
bdays = bdays[bdays.weekday < 5].difference(hols)[-10:]
>>> bdays
DatetimeIndex(['2021-02-15', '2021-02-16', '2021-02-17', '2021-02-18',
'2021-02-19', '2021-02-22', '2021-02-23', '2021-02-24',
'2021-02-25', '2021-02-26'],
dtype='datetime64[ns]', freq=None)
您可以使用 pandas 內置 function date_range 。
在您的情況下,它將是
import pandas as pd
today = '2021-02-27'
businessDays = pd.date_range(end='2021-02-27', periods=14, freq='D').to_series()
businessDays = businessDays[businessDays.dt.dayofweek < 5]
print(businessDays)
Output 像這樣:
2021-02-15
2021-02-16
2021-02-17
2021-02-18
2021-02-19
2021-02-22
2021-02-23
2021-02-24
2021-02-25
2021-02-26
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.