Announcement

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

  • Minutes and seconds coming out wrong with dhms() %tc

    I am constructing a date-time variable in 2 steps, using variables for year, month, day, hour, minutes, seconds. My code is:

    Code:
    gen enroute_date = mdy(enroute_month,enroute_day,enroute_year)
        format enroute_date %td
    gen enroute_time = dhms(enroute_date,enroute_hour,enroute_min,enroute_sec)
        format enroute_time %tc
    The variable enroute_date comes out correct every time, but the variable enroute_time is coming out with incorrect minute and seconds. The error --- the difference between enroute_hour:enroute_min:enroute_sec and the time shown in enroute_time --- is sometimes positive (later than given) and sometimes negative (earlier), and usually but not always under 60 seconds. I am not sure if the problem is with my use of dhms() or my use of format %tc. You can see the errors in the attached pic below. How can I address this? Thanks!

    Click image for larger version

Name:	Screen Shot 2021-01-03 at 1.28.57 PM.png
Views:	1
Size:	127.9 KB
ID:	1588160

  • #2
    This is a precision problem. Stata clock variables must be created as doubles, because the float storage type (which is what you get by default) does not have enough bits to store all the information needed.

    Code:
    gen double enroute_time = dhms(enroute_date,enroute_hour,enroute_min,enroute_sec)
    format enroute_time %tc
    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version 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.

    Comment


    • #3
      Thank you! This was a silly mistake on my part; I'd actually seen Nick mention double in another case, but didn't realize it was critical to precision. Also, great about dataex, I will use this from now on. Thank you so much!

      Comment

      Working...
      X