Announcement

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

  • chaning time to minutes.

    I have a variable where the data er described as 6D 21H 52M 0S (d= days, H= hours, M=minutes, S= seconds) as a str14 format.

    I need the value in minutes, how can i convert this values to total minutes or hours.

    Best Regards
    Massar

  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str14 var1
    "6D 21H 52M 0S"
    end
    
    split var1, gen(comp)
    destring comp*, replace ignore("DHMS")
    
    gen time_in_minutes = 24*60*comp1 + 60*comp2 + comp3 + comp4/60
    gen time_in_hours = time_in_minutes/60
    
    list, noobs clean
    NOTE: This code is not robust. If the variable is not consistent in the ordering of the days, hours, minutes, and seconds, or if it sometimes uses d, h, m, and s (or any other characters instead of D, H, M, S, or if it sometimes omits spaces between the different components, the code will either fail to run or, worse, run and produce incorrect results. I suggest you verify the consistency of this variable before relying on this code.

    Comment


    • #3
      This should deal with some of the problems wisely imagined by Clyde Schechter To make case consistent, use upper() or lower()


      Code:
      clear 
      set obs 1 
      gen test = "6D 21H 52M 0S" 
      split test
      gen double result = 0 
      quietly foreach v of var test? { 
          replace result = result + 24 * 60 * real(subinstr(`v', "D", "", .)) if substr(`v', -1, 1) == "D"
          replace result = result + 60 * real(subinstr(`v', "H", "", .)) if substr(`v', -1, 1) == "H"
          replace result = result + real(subinstr(`v', "M", "", .)) if substr(`v', -1, 1) == "M"
          replace result = result + real(subinstr(`v', "S", "", .))/60 if substr(`v', -1, 1) == "S" 
      }
      
      list

      Comment


      • #4
        For those who enjoy working with regular expressions, the following variant on Clyde's code is robust to the choice of upper- or lower-case characters and the inclusion of spaces as separators. It remains unrobust to the ordering of the components. The ustrregexra() replaces every sequence of 1 or more non-digit characters with 1 space.
        Code:
        * Example generated by -dataex-. To install: ssc install dataex
        clear
        input str14 var1
        "6d 21h52M 0S"
        end
        
        generate var2 = ustrregexra(var1,"\D+"," ")
        split var2, gen(comp)
        destring comp*, replace
        
        gen time_in_minutes = 24*60*comp1 + 60*comp2 + comp3 + comp4/60
        gen time_in_hours = time_in_minutes/60
        
        list, noobs clean

        Comment


        • #5
          Thank you guys, it works perfectly!

          Comment

          Working...
          X