将非标准化间隔划分为五分钟的算法-Python/SAS



假设我有一个输入(22:00-43:00)。我想从中创建以下内容:

begin = 22:00 end = 25:00
begin = 25:00 end = 30:00
begin = 30:00 end = 35:00
begin = 35:00 end = 40:00
begin = 40:00 end = 43:00

如何使用循环以最少的代码(包括部分第一个和最后一个间隔)有效地获得新的开始日期和新的结束日期?棘手的部分是,如果给定像(20:00-43:00)或(22:00-40:00)或简单地(20:00-40:00)这样的间隔,我需要解决方案来工作。

将在SAS的日期-时间变量中实现这一点,但我很感激Python中的算法,因为我知道SO上有更多的用户。

谢谢。

这里有一个SAS解决方案。5分钟对应于300秒,SAS中的日期时间以秒为单位。变量以日期时间表示,但如果只需要时间,则可以使用timepart()函数。

*Generate some sample data;
data have;
time_s = dhms('01Jan2014'd, 0, 24, 0);
time_e = dhms('01Jan2014'd, 0, 40, 0);
format time: datetime20.;
run;
proc print data=have;
run;
*Calculate intervals;
data want;
set have;
time_start=time_s;
time_end=round(time_s+150, 300);
output;
do while (time_end<time_e);
    time_start=time_end;
    time_end+300;
    if time_end>time_e then time_end=time_e;
    output;
end;
format time: datetime20.;
run;
proc print data=want;
run;

输出:

                  Obs              time_start                time_end
                   1       01JAN2014:00:22:00      01JAN2014:00:25:00
                   2       01JAN2014:00:25:00      01JAN2014:00:30:00
                   3       01JAN2014:00:30:00      01JAN2014:00:35:00
                   4       01JAN2014:00:35:00      01JAN2014:00:40:00
                   5       01JAN2014:00:40:00      01JAN2014:00:43:00

SAS具有按日期和时间间隔递增的intnx()功能。这种方法使用intnx()intck()函数来计数间隔,并使用minutes5间隔进行对齐。此外,ifn()函数用于评估是否使用起始值和结束值。

data have;
    start = dhms("01Jan1960"d, 0, 23, 0);
    end = dhms("01Jan1960"d, 0, 51, 0);
run;
data want;
    set have;
    /* Get number of intervals to loop over */
    max = intck("minute5", start, end - 1) + 1;
    do i = 1 to max;
        /* Offset start date by the loop number of intervals */
        time_start = ifn(i = 1, start, intnx("minute5", start, i - 1 , "b"));
        time_end = ifn(i = max, end, intnx("minute5", start, i, "b"));
        output;
    end;
    format time: datetime.;
    keep time:;
run;

最新更新