Search code examples
sastypeerror

SAS - Comparison of Hours


I'm new to SAS and can't seem to compare hours. Let me explain : I have a Date/Time (format : ddmmmaa:hh:mm:ss) variable that I reformatted (in format TOD8 : hh:mm:ss) to only have the time. With this specific time, I want to put it into a time slot. So if the time is between such and such time, I give him a time slot. The problem that arises for me is that I cannot compare the time. Here is my code:

data test;
    set WORK.TABLE;
    if 'hour'n > '09:00:00't and 'hour'n < '09:59:59't then 'time slot'n=0910;
    else if 'hour'n > '10:00:00't then 'time slot'n=1011;
    else 'time slot'n=-1;

run;

This gives me the result :

   Hour    |  time slot
------------------------
 08:06:00  |   1011
 09:30:00  |   1011
 11:00:00  |   1011

I think it comes from the type but I can't find any documentation that allows me to solve this problem.

If you have an idea or something that could help me understand this result it will help me a lot. Thanks in advance


Solution

  • The problem is that you applied a format considering it changed the stored value. That's a wrong statement: a format just applies a "display" pattern, no more. And this is why you can change the format to what you want without losing any information :)

    To extract a time from a datetime, use the timepart function. Then you'll be able to compare this value against other times:

    data test;
        set work.table;
    
        attrib extracted_hours format=tod5.;
        extracted_hours = timepart(your_datetime);
    
        if '09:00:00't <= extracted_hours < '10:00:00't then 'time slot'n = 0910;
        else if '10:00:00't <= extracted_hours < '11:00:0't then 'time slot'n=1011;
        else 'time slot'n=-1;
    run;