Converting time stored as a string variable to a date variable (TIME5)

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Converting time stored as a string variable to a date variable (TIME5)

ariel barak
Hello SPSS members,

I have time data (military) with some missing values in the format below
stored as a string variable. I have written the syntax below which converts
the data from 0145 into 01:45 properly. I can easily convert the String
variable to the proper TIME5 date format via the GUI but have run into
nothing but trouble trying to do this via syntax. I'm sure there is a very
simple solution.

Thanks for your help.

-Ari


data list / assaulttime (A4).
begin data
0145
0728

1334
end data.

STRING hour (A2).
STRING minute (A2).
COMPUTE hour = SUBSTR(assaulttime, 1, 2).
COMPUTE minute = SUBSTR(assaulttime, 3, 2).
EXE.

STRING assaulttime2 (A5).
COMPUTE assaulttime2 = CONCAT(hour, ':', minute).
IF assaulttime2 = '  :' assaulttime2 = ''.
EXE.
Reply | Threaded
Open this post in threaded view
|

Re: Converting time stored as a string to a date variable (TIME5)

Antro, Mark
Hi Ari,

I've added a new entry as well 145 for 01:45 just in case you have had any entries were the leading 0 was dropped. Most of the syntax comes from the Date/Time wizard (v13+), but to make it all work you need to reformat your original string so there is the delimiter between the hours and minutes, so SPSS can recognise the string as the time format hh:mm. You can delete newTime afterwards because you don't need it (DEL VAR newTime.) or have it as a scratch variable so it doesn't exist in the data editor after the execute statement (add # to the variable name throughout the syntax).

Rgds,
Antro.

data list / assaulttime (A4).
begin data
0145
0728

1334
145
end data.

STRING newTime (A5).
DO IF LENGTH(RTRIM(assaulttime)) = 4.
+   COMPUTE newTime = CONCAT(SUBSTR(assaulttime ,1,2), ":", SUBSTR(assaulttime,3)).
ELSE IF LENGTH(RTRIM(assaulttime)) = 3.
+   COMPUTE newTime = CONCAT(SUBSTR(assaulttime ,1,1), ":", SUBSTR(assaulttime,2)).
END IF.
COMPUTE assaulttime2 = number(newTime , TIME5).
VARIABLE LABEL assaulttime2 .
VARIABLE LEVEL assaulttime2 (SCALE).
FORMATS assaulttime2 (TIME5).
VARIABLE WIDTH assaulttime2 (5).
EXE.