Announcement

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

  • converting date into number of days

    Hello everyone,

    I was wondering if it is possible to create a new variable 'day' that counts the number of days. I have a panel dataset with dates and I would like to create a new variable where the first date in the dataset has the number 1, the second date in the dataset number 2, etc.
    What I have come up with so far is:
    gen day = .
    replace day=1 if date=="2020-10-14", where 2020-10-14 is the first date in the dataset.
    This works, but I have to change all the dates manually
    However I was wondering if there is a simpler way, so that I am not spending a lot of time converting these days to the number of days.

    Thanks in advance!

  • #2
    The implication of your question is that you are holding daily dates as a string variable. Perhaps not, perhaps so, but please give a data example that makes this clear.

    We ask that people read the FAQ Advice before posting. This may seem tedious or officious, but in practice it stops you wasting your time and people wasting their time guessing whether you have one thing or another. https://www.statalist.org/forums/help#stata is crucial here.

    Beyond that, do you care about referring dates to the first date in

    1. the entire dataset

    2. each panel if they start on different dates

    ?

    Comment


    • #3
      My date variable is indeed a string variable. I had no clue how to convert the dates to the number of days if the variable was another type of variable.
      I care about referring dates to the first date in the entire dataset

      Comment


      • #4
        Again, please use dataex (see the link in #2). This is a guess based on the information so far.

        Code:
        * read relevant parts of this 
        help datetime 
        
        gen better_date = daily(date, "YMD") 
        format better_date %td 
        
        * find the minimum, returned in r(min) 
        su better_date 
        
        gen day = better_date - r(min) + 1

        Comment


        • #5
          thank you Nick Cox

          Comment

          Working...
          X