Announcement

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

  • extracting year from an elapsed and formatted date

    Dear all,

    I am having an issue extracting the year from my date variable.

    My date variable is already elapsed and formatted in a way that I can read the year followed by the month. Eg: 2013m1, 2013m2, ..... , 2015m12 - this variable is called modate

    Now I need a variable that shows me only the year. I tried generating a variable year=modate and then formatting it so that it only displays the year;


    gen year=modate
    format year %ty

    but then I get strange results such as 1961 or numbers like 636.

    Can someone help me out?

    Thanks!!
    Cami

  • #2
    Hi Camila,

    please have a look at the FAQ (also linked from the top of each page) to learn how to post questions in a way so that we can answer them quickly. This involves using code delimiters, and sharing example data using -dataex-.

    If you don't, our answers are mainly guesswork. It is these kinds of questions that don't get answers quickly, because most experienced users here don't like guesswork.

    Thus said, here's my guesswork on your topic: From what you write, I assume you have a Stata Internal Format (SIF) date variable, correctly formatted:
    Code:
    * make up example data
    clear
    set obs 36
    generate modate=_n+635
    format modate %tm
    list
    Note that Stata internally stores a monthly date as "months counted from January, 1960". This means that January, 2013 equals month number 636. See -help datetime- for background information on this; it is a good idea to read through it in order to understand the concept.

    Converting this month count to a year number is, mathematically, nothing more than dividing it by 12 and adding 1960 to the result:
    Code:
    * manually converted
    generate manual_year=((modate / 12) + 1960)
    However, to perform these kinds of conversion tasks, Stata has a few more elaborate functions for it; see -help datetime, marker(s6)-. They can, for instance, account for leap seconds, which a manual function cannot (this is not required in your example, but it may be with other conversion tasks). So, the Stata way to do your conversion would be:
    Code:
    * Stata-ish converted
    generate year=yofd(dofm(modate))
    Kind regards
    Bela
    Last edited by Daniel Bela; 04 Jun 2018, 07:39. Reason: corrected link to help

    Comment

    Working...
    X