Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Re: hours:minutes:seconds

From   Gary Longton <>
Subject   Re: st: Re: hours:minutes:seconds
Date   Mon, 16 Dec 2002 13:34:12 -0800

Christa Scholtz wrote:

> I have a data field where the duration of an event is recorded in this
> format:
> hour:minute:second
>  eg:  an event that lasts 5 hours, 27 minutes and 13 seconds is 5:27:13.
> How do I get Stata to convert this into total number of seconds?

and Radu Ban replied:

you can try sth like:
if your_time is the variable you have for time

gen str8 stime = your_time
gen shours = substr(stime, 1, 2) *takes the first two digits
gen hours = real(shour) *reads first two digits as number
gen sminutes = substr(stime, 4, 2) *takes digits 4 and 5
gen minutes = real(sminutes)
gen sseconds = substr(stime, 7, 2)
gen seconds = real(sseconds)

*now add up
gen totsecs = 3600*hours + 60*minutes + seconds
Radu's approach assumes that the original time string will always have 2-digit hours, which will often be too restrictive, and won't work for Christa's example.

An easier one-step approach for parsing the time string into the 3 component numeric variables would be to use Nick Cox's -split- program (available on SSC), which could be followed with Radu's expression for total seconds.

- Gary

* For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index