string Stata:如何将字符串变量更改为日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18226747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stata: how to change a string variable to a date?
提问by finstats
I'm new to Stata, and I'm wondering how can I change a string variable which contains a date to a date format.
我是 Stata 的新手,我想知道如何将包含日期的字符串变量更改为日期格式。
The data in the variable looks like this:
变量中的数据如下所示:
yyyy-mm-dd
yyyy-mm-dd
Should I first remove the dashes so that Stata can recognize the format in order to later use gen var = date()
?
我应该先删除破折号,以便 Stata 可以识别格式以便以后使用gen var = date()
吗?
Thank you for your help.
感谢您的帮助。
回答by sechilds
The Stata date
function is smart about removing separator characters. See help datetime_translationunder the section "the date function"
Statadate
函数在删除分隔符方面很聪明。请参阅“日期函数”部分下的帮助 datetime_translation
If your dates are in v1
and in the form yyyy-mm-dd
you can specify the commands:
如果您的日期在v1
表单中,yyyy-mm-dd
您可以指定命令:
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.
的YMD
被称为掩模,它告诉Stata的其中指定日期的部件的顺序。第二行将为变量分配 Stata 每日日期格式,这意味着当您查看数据中的该变量时,它将以人类可读的形式显示。但是,日期存储为自 1960 年 1 月 1 日以来的天数。
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.
试验该date
功能的最佳方法是使用该display
命令。第一行将显示一个整数,表示自 1960 年 1 月 1 日以来的天数。第二行将以人类可读的格式显示日期。
display date("2013-08-14", "YMD")
display %td date("2013-08-14", "YMD")
回答by No Idea For Name
you can look hereto see how to convert to data in Stata or do like this
你可以在这里查看如何在Stata中转换为数据或这样做
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)