日期时间范围中前一天/月/年的第一个可用日期 [英] First available date previous day/month/year from a datetime range
问题描述
我有一个带有日期(dfDates
)的datetime实例:
I have a datetime instance with dates (dfDates
):
2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...
对于最后一天(在这里:2017-03-04
),我计算前一天/月/年/等.如下:
For the last day (here: 2017-03-04
) I calculate the previous day/month/year/etc. as follows:
def previous_day(dtToday):
return dtToday - pd.DateOffset(days=1)
这将返回2017-03-03
.但是,该工作日在我的日期范围(dfDates
)中不可用.
This returns 2017-03-03
. However, this business day is not available in my range of dates (dfDates
).
因此,我正在寻找一种可靠的方法来查找最接近前一天/月/年/等的日期.在这种情况下,前一天应该返回2017-03-02
.
I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02
.
请注意,我了解您可以执行类似索引-1
的操作来获取前一天.但是,如果使用上个月(一个月中并非总是30
天)甚至是上一年(一年中并不总是有252
个工作日),则变得非常复杂.因此,是否有一种健壮的方法来获取最接近的可用日期?
Note, I understand that you can do something like index -1
to get the previous day. It becomes however complicated when taking the previous month (there are not always 30
days in a month) and even the previous year (there are not always 252
working days in a year). Is there therefore a robust method to get the closest available date?
更新
我也了解您可以按以下方式使用timedelta:
I understand also that you can use timedelta as follows:
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract)
但是,这与dtToday
有什么关系,如何将其与dfDates
链接?在我的情况下,dtToday
并不总是datetime.today()
.有时是随机日期.
However, how does that relate to dtToday
and how can I link it with dfDates
? dtToday
in my case is not always datetime.today()
. Sometimes its a random date.
推荐答案
我是这样解决的:
-
dtToday
=参考日期 -
dtDates
=日期的时间序列 可用日期 -
nbOffset
=我们想要的天数/月数/年数 回去
dtToday
= the reference datedtDates
= a datetime sequence of the available datesnbOffset
= the number of days/months/years we want to go back
代码:
def previous_day(dtToday, dtDates, nbOffset):
prevx = dtToday - pd.DateOffset(days=nbOffset)
return test_day_in(prevx, dtDates)
def previous_month(dtToday, dtDates, nbOffset):
prevx = dtToday - pd.DateOffset(months=nbOffset)
return test_day_in(prevx, dtDates)
def previous_year(dtToday, dtDates, nbOffset):
prevx = dtToday - pd.DateOffset(years=nbOffset)
return test_day_in(prevx, dtDates)
def test_day_in(dtTest, dtDates):
if dtTest in dtDates:
return dtTest
else:
return tryNextDay(dtTest, dtDates)
def tryNextDay(dtTest, dtDates):
# if not outside the bound
if (dtTest < dtDates.min()):
return dtDates.min()
# check if next day exist
if (dtTest + pd.DateOffset(days=1) <= dtDates.max()):
return previous_day(dtTest + pd.DateOffset(days=2), dtDates, 1) # 2-1
else:
print('warning, tryNextDay triggered')
# should not be triggered, it should take by default the dtDates.min() if far outside range
return dtTest
这篇关于日期时间范围中前一天/月/年的第一个可用日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!