Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to transform integer variable to time variable

    Hello Statalists,
    I have a numeric integer variable called Hour that ranges from 0 to 2300. I want to transform it to time hour. 0 to 00:00; 100 to 01:00; 200 to 01:00; ...; 2300 to 23:00.
    Please, how do I do that?

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float id int hour
     1    0
     2  100
     3  200
     4  300
     5  400
     6  500
     7  600
     8  700
     9  800
    10  900
    11 1000
    12 1100
    13 1200
    14 1300
    15 1400
    16 1500
    17 1600
    18 1700
    19 1800
    20 1900
    21 2000
    22 2100
    23 2200
    24 2300
    end

    Thank you!

  • #2
    You could transform it to Stata date-time variable with

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float id int hour
     1    0
     2  100
     3  200
     4  300
     5  400
     6  500
     7  600
     8  700
     9  800
    10  900
    11 1000
    12 1100
    13 1200
    14 1300
    15 1400
    16 1500
    17 1600
    18 1700
    19 1800
    20 1900
    21 2000
    22 2100
    23 2200
    24 2300
    end
    
    keep if mod(hour,400) == 0 
    
    gen double time = clock(string(hour/100), "h")
    
    format time %tcHH:MM 
    
    list, sep(0)
    
        +-------------------+
         | id   hour    time |
         |-------------------|
      1. |  1      0   00:00 |
      2. |  5    400   04:00 |
      3. |  9    800   08:00 |
      4. | 13   1200   12:00 |
      5. | 17   1600   16:00 |
      6. | 21   2000   20:00 |
         +-------------------+
    But for many purposes keeping it as it is or dividing by 100 would be fine. But that wouldn't be true if you had also e.g. 830 when you need more care, and the code above needs elaboration.

    Comment


    • #3
      Hi prof. Nick Cox, Thank you very much!
      And thank you for your suggestion. I was indeed in doubt if I could leave the way it is originally since I will just need it to collapse by day and id.
      Many thanks!

      Comment

      Working...
      X