1
votes

I have imported an Excel file into Stata containing a string variable with dates in the Month/Day/Year Format, as following:

     +--------------------------+
     |     country     Election |
     |--------------------------|
  1. | New Zealand   11/29/1969 |
  2. | New Zealand   11/25/1972 |
  3. | New Zealand   11/27/1999 |
  4. | New Zealand   11/25/1972 |
  5. | New Zealand   09/17/2005 |
     +--------------------------+

My intention is to transform the date, so that only the year appears.

I have used gen year = date(Election, "MDY") to create a new date variable with the float type. However, I don't know how to proceed. How could I transform these dates into years only?

1
Check out help datetime especially the section on "SIF-to-SIF conversion" which is what you want to do - convert from "date" to "yearly". I recommend you generate a new variable rather than replace the existing variable. - user4690969
Thank you! I checked it out and ran the command: generate Year_only = yofd( year). It worked perfectly. - Adrian

1 Answers

0
votes

You have the answer, but we'll spell it out for the benefit of any others interested.

Your variable year is misnamed, as it is a daily date variable. I'd recommend using the function daily() rather than date() to underline what is happening. It's the same code under different guises. Then you need yofd() to convert.

clear 
input str11 (country Election) 
"New Zealand"   "11/29/1969"
"New Zealand"   "11/25/1972"
"New Zealand"   "11/27/1999"
"New Zealand"   "11/25/1972"
"New Zealand"   "09/17/2005"
end 
gen dailydate = daily(Election, "MDY") 
format dailydate %td 
gen yeardate = yofd(dailydate) 
list 


     +-------------------------------------------------+
     |     country     Election   dailydate   yeardate |
     |-------------------------------------------------|
  1. | New Zealand   11/29/1969   29nov1969       1969 |
  2. | New Zealand   11/25/1972   25nov1972       1972 |
  3. | New Zealand   11/27/1999   27nov1999       1999 |
  4. | New Zealand   11/25/1972   25nov1972       1972 |
  5. | New Zealand   09/17/2005   17sep2005       2005 |
     +-------------------------------------------------+