Announcement

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

  • Geting year from monthly date

    I generated a variable for year/month as below. The variable dt_fim corresponds to a date as YMD, but I just wanted to keep year and month in another variable.


    Code:
    gen anom_fim = monthly(string(year(dt_fim))+" "+string(month(dt_fim)),"YM")
    format anom_fim %tm
    Code:
    anom_fim
    2014m11
    2014m11
    2014m12
    2014m12
    2014m11
    How I am having trouble to get the year of this created variable (I have dropped the dt_fim variable). I tried both commands below but they brought

    Code:
    gen ano = year(anom_fim)
    
    anom_fim    ano
    2014m11    1961
    2014m11    1961
    2014m12    1961
    2014m12    1961
    2014m11    1961
    Code:
    gen ano2 = real(substr(string(anom_fim),1,4))
    
    anom_fim    ano2
    2014m11    658
    2014m11    658
    2014m12    659
    2014m12    659
    2014m11    658
    How can I get the year from variable anom_fim?

  • #2
    %tm variables are integers that count months since January of 1960. You can accomplish what you want with

    Code:
    generate ano = 1960 + floor(anom_fim/12)

    Comment


    • #3
      The -year()- function pulls the year out of daily date variables, not any date variable whatsoever.

      Comment


      • #4
        The command that Dimitriy sent works well for me! But if I want to get a specific year and month from this variable anom_fim which informs month/year in a monthly display format?

        Comment


        • #5
          I am not entirely sure what you mean.

          You can create year and month by first converting your %tm (monthly) date variable to %td (daily) and then using the year() and month() functions, which expect their arguments to be daily dates:

          Code:
          gen year = year(dofm(ano_fim))
          gen month = month(dofm(ano_fim))
          You can also do this without converting with arithmetic:

          Code:
          gen year2 = 1960 + floor(ano_fim/12)
          gen month2 = mod(ano_fim,12)+1
          The idea behind this approach is that %tm is just an integer counting months since January of 1960 (zero).

          You can also do it on the fly (without creating year and month variables) like this:
          Code:
          list if year(dofm(ano_fim))==2015 & month(dofm(ano_fim))==6
          Last edited by Dimitriy V. Masterov; 21 Jul 2015, 19:30.

          Comment

          Working...
          X