How do I convert (daily) date to month date?

2019-08-27 17:47发布

问题:

In Stata, how do I convert date in the form of:

09mar2005 00:00:00

to a month-year variable?

If it matters, the date format is %tc.

What I have in mind is to plot monthly averages (instead of the daily average I have) of variables across time.

回答1:

To get where you are now, you or somebody else may have done something like this:

clear 
set obs 1 
gen earlier = "09mar2005 00:00:00"
gen double nowhave = clock(earlier, "DMY hms") 
format nowhave %tc 
list 

     +-----------------------------------------+
     |            earlier              nowhave |
     |-----------------------------------------|
  1. | 09mar2005 00:00:00   09mar2005 00:00:00 |
     +-----------------------------------------+

Note that a string date and a numeric date-time variable with appropriate date-time format %tc just look the same when you list them, but they are quite different beasts.

To get where you want to be -- with a monthly date -- you convert from clock (date-time) to daily to monthly:

gen mdate = mofd(dofc(nowhave)) 

format mdate %tm 

list 

     +--------------------------------------------------+
     |            earlier              nowhave    mdate |
     |--------------------------------------------------|
  1. | 09mar2005 00:00:00   09mar2005 00:00:00   2005m3 |
     +--------------------------------------------------+

All is documented at help datetime. The function names stand for month of daily date and daily date of clock.



标签: stata