计算从今天起 5 天的日期,在接下来的 5 天内为周末的每一天添加额外的一天 [英] Calculate date 5 days from today, adding an extra day for each day in the next 5 days that is a weekend day
问题描述
我正在使用 Robot Framework 进行测试,需要创建自己的 Python 关键字.
I am testing using Robot Framework and need to create my own Python keyword.
以当前日期为第 0 天(明天为第 1 天),我试图计算从今天起 5 天后的日期.如果接下来 5 天中的任何一天是星期六,我需要在计算中多加一天.如果任何一天是星期日,则相同.
Taking the current date as day 0 (tomorrow as day 1), I am trying to calculate what the date will be 5 days from today. If any of the days in the next 5 days is a Saturday I need to add an extra day to my calculation. Same if any of the days is a Sunday.
作为一个 Python 初学者,我有点超出我的深度,所以任何帮助将不胜感激
As a Python beginner, I'm a little out of my depth so any help would be much appreciated
推荐答案
使用 NumPy,您可以使用 np.busday_offset
:
Using NumPy, you can find add or subtract business days using np.busday_offset
:
由于 2016-03-27
是星期日,向前滚动返回第一个有效工作日,2016-03-28
:
Since 2016-03-27
is a Sunday, rolling forward returns the first valid business day, 2016-03-28
:
import numpy as np
np.busday_offset('2016-03-27', 0, roll='forward')
# numpy.datetime64('2016-03-28')
要获取datetime
对象,调用item()
:
np.busday_offset('2016-03-27', 0, roll='forward').item()
# datetime.date(2016, 3, 28)
要提前 5 个工作日,请将第二个参数更改为 5:
To advance 5 business days, change the second argument to 5:
np.busday_offset('2016-03-27', 5, roll='forward').item()
# datetime.date(2016, 4, 4)
要返回 5 个工作日,请使用负偏移量和 roll='backward':
To go back 5 business days, use a negative offset and roll='backward':
np.busday_offset('2016-03-27', -5, roll='backward').item()
# datetime.date(2016, 3, 18)
np.busday_offset('2016-03-28', -5, roll='backward').item()
# datetime.date(2016, 3, 21)
<小时>
这是一个日历供参考:
Here's a calendar for reference:
March 2016 April 2016
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 1 2
6 7 8 9 10 11 12 3 4 5 6 7 8 9
13 14 15 16 17 18 19 10 11 12 13 14 15 16
20 21 22 23 24 25 26 17 18 19 20 21 22 23
27 28 29 30 31 24 25 26 27 28 29 30
这篇关于计算从今天起 5 天的日期,在接下来的 5 天内为周末的每一天添加额外的一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!