Announcement

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

  • Calculating time duration

    Hi,

    I have a data set on the hours worked "starting time" and "end time" in 24 hrs format. I need to calculate the duration as the number of hours worked.

    time_t time_fr
    04:00 06:00
    06:00 06:30
    06:00 06:30
    21:30 04:00


    i applied the date format ("DMY hms") and brought the same into the following format

    time_from time_to

    01jan1960 06:00:00 01jan1960 04:00:00
    01jan1960 06:30:00 01jan1960 06:00:00
    01jan1960 06:30:00 01jan1960 06:00:00
    01jan1960 04:00:00 01jan1960 21:30:00

    However, in those cases (4th row) where the hours worked extended to the next day, I get the wrong figure (highlighted in bold).how can I fix this?

    appreciate your help.

    Thanks in advance.

  • #2
    Your example data is confusing. You have interchanged the values in time_from and time_to when you show them in the two different places. I'm going to assume that the second one is correct because common sense says that in ordinary circumstances time_from should precede time_to.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input double(time_fr time_t)
    14400000 21600000
    21600000 23400000
    21600000 23400000
    77400000 14400000
    end
    format %tc time_t
    format %tc time_fr
    
    replace time_t = time_t + msofhours(24) if time_t < time_fr & !missing(time_fr)
    will, I believe, solve your problem.

    In the future, when showing data examples, please use the -dataex- command to do so, as I have here. If you are running version 17, 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data. Also, in this case, it would have prevented the interchanging of the two variable names.

    Comment


    • #3
      It worked. Thank you, Clyde Schechter.

      Comment

      Working...
      X