user10536878
user10536878

Reputation:

Change seconds to string

I have these seconds representing the time of completing each lap:

* Example generated by -dataex-. To install: ssc install dataex
clear
input float(lap lapruntime)
 1 1386
 2  816
 3 1835
 4 2048
 5  751
 6 2456
 7 1947
 8 1640
 9 2090
10 1372
end

Is there a way to change these to an hours:minutes:seconds string?

I thought I can do this with the command:

format %tcHH:MM:SS lapruntime 

However, this gives me some strange results.

I would also like to do the same for the difference between each lap run time.

Upvotes: 1

Views: 52

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

As already mentioned, there is a community-contributed function for egen in this territory, but it is immensely better just to use official offerings and concoct your own code. None of your example times is more than 60 minutes, so getting the minutes one way and the seconds another way leads to a concatenation. A small but needed trick is to use %02.0f to ensure that seconds fewer than 10 seconds are shown conventionally.

* Example generated by -dataex-. To install: ssc install dataex
clear
input float(lap lapruntime)
 1 1386
 2  816
 3 1835
 4 2048
 5  751
end

egen wanted = elap(lapruntime) 

list 

     +-----------------------------+
     | lap   laprun~e       wanted |
     |-----------------------------|
  1. |   1       1386   0:00:23:06 |
  2. |   2        816   0:00:13:36 |
  3. |   3       1835   0:00:30:35 |
  4. |   4       2048   0:00:34:08 |
  5. |   5        751   0:00:12:31 |
     +-----------------------------+

gen minutes = floor(lapruntime/60)
gen seconds = mod(lapruntime, 60)
egen WANTED = concat(minutes seconds), p(:) format(%02.0f)

list 

     +----------------------------------------------------------+
     | lap   laprun~e       wanted   minutes   seconds   WANTED |
     |----------------------------------------------------------|
  1. |   1       1386   0:00:23:06        23         6    23:06 |
  2. |   2        816   0:00:13:36        13        36    13:36 |
  3. |   3       1835   0:00:30:35        30        35    30:35 |
  4. |   4       2048   0:00:34:08        34         8    34:08 |
  5. |   5        751   0:00:12:31        12        31    12:31 |
     +----------------------------------------------------------+

Those paid by the reciprocal of lines of code can imagine a way to do it in one line as

strofreal(floor(lapruntime/60)) + ":" + strofreal(mod(lapruntime, 60), "%02.0f")

Upvotes: 1

Related Questions