Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stata: how to change a string variable to a date?

I'm new to Stata, and I'm wondering how can I change a string variable which contains a date to a date format.

The data in the variable looks like this:

yyyy-mm-dd

Should I first remove the dashes so that Stata can recognize the format in order to later use gen var = date() ?

Thank you for your help.

like image 560
finstats Avatar asked Aug 14 '13 08:08

finstats


2 Answers

The Stata date function is smart about removing separator characters. See help datetime_translation under the section "the date function"

If your dates are in v1 and in the form yyyy-mm-dd you can specify the commands:

generate v2 = date(v1, "YMD")
format %td v2

The YMD is called a mask, and it tells Stata the order in which the parts of the date are specified. The second line will assign the variable the Stata daily date format, which means that when you look at that variable in the data, it will be shown in human readable form. The date is stored, however, as the number of days since January 1, 1960.

The best way to experiment with the date function is to use the display command. The first line will display an integer representing the number of days since January 1, 1960. The second line will display the date in a human readable format.

display date("2013-08-14", "YMD")
display %td date("2013-08-14", "YMD")
like image 115
sechilds Avatar answered Oct 21 '22 13:10

sechilds


you can look here to see how to convert to data in Stata or do like this

tostring datedx, replace
generate str4 dxyr1= substr(datedx,1,4)
generate str2 dxmo1 = substr(datedx,6,7)
generate str2 dxda1 = substr(datedx,9,10)
destring dx*, replace
gen datedx1 = mdy(dxmo1, dxda1, dxyr1)
like image 29
No Idea For Name Avatar answered Oct 21 '22 13:10

No Idea For Name