Announcement

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

  • Please Help Formatting Date in Units to MDY

    Hello,

    I am trying to convert the date in units, for example 613608, into a date variable preferable in the *MYD* format. The units are based on "hours since 1800-01-01 00:00:0.0". So in this case I believe 613608 should result in January 1st, 1870, which is the first date in the dataset. I have tried to look up the syntax for the datetime commands, but I am still very confused.

    I have provided the code below with the first 4 observations in my dataset. Any help would be greatly appreciated.

    Code:
    input long time float(lat lon pdsi)
    613608 -46.25 168.75    .1647371
    613608 -43.75 -73.75    .6625475
    613608 -43.75 -71.25    .7405886
    613608 -43.75 168.75   .10170344
    Thank you!

  • #2
    Stata has different types of internal representations of time: dates and datetime (see -help datetime-). Only datetime representations have the necessary precision to deal with units of time smaller than a day, so you must perform any calculation on and using functions for datetime.

    The main bit is that since you have number of hours, and datetimes are recorded in units of milliseconds, a simple conversion is needed from hours to ms (= 60*60*1000). This is the offset, to be added to the time of your reference date. The date can be computed using the -clock()- function.

    The rest then is just formatting to some desirable display format. Additional formatting can be found at -help datetime display formats-.

    In the code below I used a macro to store the conversion factor, but this is a matter of taste and is unnecessary. However, it is good practice to store things like constants in their own variables (or macros, here) so they do not appear as hard-coded "magic" numbers in code.

    Code:
    local hours_to_ms = 60 * 60 * 1000
    gen double want = clock("1jan1800", "DMY") + time * `hours_to_ms'
    format %tcNNCCYYDD want
    list
    Result

    Code:
         +------------------------------------------------+
         |   time      lat      lon       pdsi       want |
         |------------------------------------------------|
      1. | 613608   -46.25   168.75   .1647371   01187001 |
      2. | 613608   -43.75   -73.75   .6625475   01187001 |
      3. | 613608   -43.75   -71.25   .7405886   01187001 |
      4. | 613608   -43.75   168.75   .1017034   01187001 |
         +------------------------------------------------+

    Comment


    • #3
      Thank you Leonardo it worked perfectly!

      Comment

      Working...
      X