Announcement

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

  • Extract Year and Month from date

    Hi,

    I have the following dates:
    HTML Code:
    date
    1972q2
    1972q3
    1972q4
    1973q1
    1973q2
    1973q3
    1973q4
    1974q1
    1974q2
    I would like to extract the year and month. I have tried the code:
    Code:
    gen year = year(date)
    gen month = month(date)
    which return the following because of the way my variable "date" is stored in Stata:
    HTML Code:
    date    year    month
    1972q2    1960    2
    1972q3    1960    2
    1972q4    1960    2
    1973q1    1960    2
    1973q2    1960    2
    1973q3    1960    2
    1973q4    1960    2
    1974q1    1960    2
    1974q2    1960    2
    Can someone help me with that? Thank!

  • #2
    Year is doable, but how is month defined? For example, Q1 is typically Jan, Feb, and March. Which should it be here?

    The reason your code is not working is that year() and month() expect the argument to be a %td variable, not a %tq one. Both types are integers, but the first is days since 01/01/1960 and the second is quarters since Q1 of 1960. Underneath the label, 1972q1 is just 48, which is also 02/18/1960.

    To get things to work, you need to do the conversion from tq to td first (help datetime##s6) :

    Code:
    gen year = year(dofq(yq))
    gen month = month(dofq(yq))
    The month will be the first month of the quarter: January, April, July, and October.
    Last edited by Dimitriy V. Masterov; 19 Jul 2015, 23:35.

    Comment


    • #3
      Thanks a lot Dimitriy!

      Comment

      Working...
      X