Stefano Lombardi
Stefano Lombardi

Reputation: 1591

extract quarter from date variable in Stata

I am trying to extract the quarter from a date variable that looks like dat in the following example:

clear all

input str20 str
    "12Jan1998"
    "29Dec2000"
end

gen dat = date(str, "DMY")
format dat %tdDD-NN-CCYY

I am trying to use the quarter() function, like in:

gen quart = quarter(dofq(dat))

What I get is clearly wrong. Can you please suggest a way to solve this? According to the example, what I would like to get in the end is 1 and 4.

Upvotes: 1

Views: 8152

Answers (2)

Nick Cox
Nick Cox

Reputation: 37208

As you constructed a daily date, all you need is quarter(). I use here daily() not date(). It's the same function, but the name is more specific.

. clear all

. input str9 str

           str
  1. "12Jan1998"
  2. "29Dec2000"
  3. end

. gen date = daily(str, "DMY")

. format date %tdDD-NN-CCYY

. gen quarter = quarter(date) 

. list  

     +----------------------------------+
     |       str         date   quarter |
     |----------------------------------|
  1. | 12Jan1998   12-01-1998         1 |
  2. | 29Dec2000   29-12-2000         4 |
     +----------------------------------+

Upvotes: 1

user4690969
user4690969

Reputation:

The help quarter documentation tells us that it accepts as an argument "%td dates" so you befuddled it by giving it an argument converted from that to a "%tq date". So

gen quart = quarter(dat)

will do what you want.

Upvotes: 1

Related Questions