Announcement

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

  • using a separate time variable and am/pm indicator variable to generate a military time variable

    Hi,

    I briefly dug into this and could not find an answer. I have 3 variables: a date variable, a time variable, and an am/pm indicator for the date/time an incident was reported and for when it occurred. For each, I'd like to replace the 2 time variables with 1 military time variable. I think this involves the clock function but I'm getting error codes. Could anyone help? My dataset looks like this:

    inci_id date_rept time_rept_1 time_rept_2 date_occu time_occur_1 time_occur_2
    20013 1/1/2020 12:24:00 AM 1/1/2020 12:15:59 AM

    Thank you!
    Tom


  • #2
    I have no idea what you intend by "military time". The starting point for whatever you want to do in Stata is transforming your strings into a Stata Internal Format datetime variable, as described in the output of help datetime and more fully in the PDF documentation it links to.

    Here is one approach.
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int inci_id str8(d t) str2 m
    20013 "1/1/2020" "12:24:00" "AM"
    20014 "1/1/2020" "01:24:00" "AM"
    20015 "1/1/2020" "12:24:00" "PM"
    20016 "1/1/2020" "01:24:00" "PM"
    end
    
    generate double dt = clock(d+t,"MDYhms")
    format dt %tc
    replace dt = dt - 12*60*60*1000 if hh(dt)==12 & m=="AM"
    replace dt = dt + 12*60*60*1000 if hh(dt)!=12 & m=="PM"
    list
    Code:
    . list
    
         +---------------------------------------------------------+
         | inci_id          d          t    m                   dt |
         |---------------------------------------------------------|
      1. |   20013   1/1/2020   12:24:00   AM   01jan2020 00:24:00 |
      2. |   20014   1/1/2020   01:24:00   AM   01jan2020 01:24:00 |
      3. |   20015   1/1/2020   12:24:00   PM   01jan2020 12:24:00 |
      4. |   20016   1/1/2020   01:24:00   PM   01jan2020 13:24:00 |
         +---------------------------------------------------------+
    Last edited by William Lisowski; 04 Nov 2021, 19:34. Reason: Reason: Improved the generate and replace commands.

    Comment


    • #3
      William Lisowski that is what I meant by military time and thank you very much for taking the time to write out that code. Very helpful.

      Comment

      Working...
      X