2017-04-11 56 views
1

我已導入Excel文件到塔塔含在月/日/年格式的日期字符串變量,如下:我怎麼能轉換長日期,年?

 +--------------------------+ 
    |  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 | 
    +--------------------------+ 

我的目的是把日期,以便顯示只有一年。

我已經使用gen year = date(Election, "MDY")創建與浮子類型的新日期變量。但是,我不知道如何繼續。我怎樣才能將這些日期轉換成僅僅幾年?

+1

退房'幫助datetime'特別是在「SIF到SIF轉化」,這是你想要做的部分 - 從「日期」轉換爲「年」。我建議你'generate'一個新的變量,而不是'replace'已有的變量。 – 2017-04-11 19:48:22

+1

謝謝!我檢查了它並運行命令:generate Year_only = yofd(year)。它工作完美。 – Adrian

回答

0

你有答案,但我們會把它拼出來,以利於任何其他感興趣的人。

您的變量year是錯誤的,因爲它是一個每日日期變量。我建議使用函數daily()而非date()強調發生了什麼。這是不同名稱下的相同代碼。然後,你需要yofd()轉換。

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 | 
    +-------------------------------------------------+