Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • String variable to date format

    Hi,

    I am encountered with a problem in converting a string variable to date format to enable time series analysis.
    My string variable looks like this:
    0117
    0217
    0317
    0417
    .
    .
    .
    1217
    0118
    0218
    .
    .
    .
    .
    1118
    1218


    Can you please help me convert this variable from a string variable to date format.


  • #2
    There are several different ways you could do this, and I'm not really sure which is simplest. One approach is:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str4 string_date
    "0117"
    "0217"
    "0317"
    "0417"
    "1217"
    "0118"
    "0218"
    "1118"
    "1218"
    end
    
    gen monthly_date = mofd(mdy(real(substr(string_date, 1, 2)), 1, ///
                                real("20"+substr(string_date, 3, 2))))
    format monthly_date %tm
    Here's another:
    Code:
    replace string_date = substr(string_date, 1, 2) + "m20" + substr(string_date, 3, 2)
    gen monthly_date = monthly(string_date, "MY")
    format monthly_date %tm
    In the future, when showing data examples, please use the -dataex- command to do so, as I have in this response. If you are running version 15.1 or a fully updated version 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Comment

    Working...
    X