Convert string month to numeric

时间:2015-07-31 20:06:49

标签: date stata

I have a variable period that contains a month as an abbreviated string (i.e. "JAN", "FEB", "MAR", etc). How do I convert period to a numeral (i.e. 1, 2, 3, etc)?

My solution is:

gen fake_date_s = "2000"+period+"1"
gen fake_date = date(fake_date_s, "YMD")
gen month = month(fake_date)

2 个答案:

答案 0 :(得分:4)

I don't think it's ugly:

clear

input ///
str3 period
JAN
FEB
DEC
end

list

gen monthnum = month(date("2000" + period + "1", "YMD"))

list

This also works:

gen monthnum = month(date(period, "M"))

as it sets the day and the year in the daily date to 01 and 1960, by default.

I'm sure you can find an alternative that doesn't use date functions, but why not use them?

答案 1 :(得分:2)

Another approach is:

local i=1
foreach m in `c(Mons)' {
    replace month = "`i'" if month == upper("`m'")
    local ++i
}

destring month, replace