Announcement

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

  • Computing time span between dates

    Hello,

    I have a dataset that records a series of variables for a large number of observations, including the date at which the observation was made. I want to create a new variable, that measures the distance between the moment of observation and a given date, in this case, 13 May 2019.

    What is the easiest way to implement this?

  • #2
    if your dates are in Stata internal format (see "help datetime") you can just subtract (though the exact method depends on whether your data are in long or wide form); if your dates are not in the SIF, then you need to get them there; for help with exact code, please post an example using -dataex- (see the FAQ for advice)

    Comment


    • #3
      A daily date in Stata is the number of days since 1 January 1960, so time spans are obtained by subtraction. Here I used scalar constants, but the principle is the same for a daily date variable and a daily date scalar or for two daily date variables.

      Code:
      . di mdy(1, 1, 1960)
      0
      
      . di mdy(5, 16, 2020)
      22051
      
      . di mdy(5, 16, 2020) - mdy(5, 1, 2020)
      15
      See

      Code:
      help datetime

      Comment


      • #4
        Thank you so much!

        I also managed to do this in a more convoluted way:

        Code:
        gen ds_day=.
        replace ds_day=clock("2015-03-29: 03:00:00", "YMD hms") if year==2015
        replace ds_day=clock("2016-03-27: 03:00:00", "YMD hms"), if year==2016
        replace ds_day=clock("2016-03-27: 03:00:00", "YMD hms") if year==2016
        replace ds_day=clock("2017-03-26: 03:00:00", "YMD hms") if year==2017
        replace ds_day=clock("2018-03-25: 03:00:00", "YMD hms") if year==2018
        replace ds_day=clock("2019-03-31: 03:00:00", "YMD hms") if year==2019
        
        format ds_day %tc
        replace ds_day=dofc(ds_day)
        format ds_day %td
        
        gen distance=.
        replace distance=date-ds_day

        Comment


        • #5
          A time of 3 am is gratuitous if it is going to be discarded any way. Your code seems equivalent to this: .

          Code:
          gen ds_day = mdy(3, 29, year) if year == 2015 
          replace ds_day = mdy(3, 27, year) if year == 2016
          replace ds_day = mdy(3, 26, year) if year == 2017 
          replace ds_day = mdy(3, 25, year) if year == 2018
          replace ds_day = mdy(3, 31, year) if year == 2019 
          format ds_day %td 
          
          gen distance = date - ds_day

          Comment

          Working...
          X