Announcement

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

  • Converting string date variables to numeric

    I have string date variables. My attempts below to convert these to numeric variables have failed. Any help much appreciated.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str9 date
    "01-Apr-12"
    "01-Apr-12"
    "01-Apr-12"
    "02-Apr-12"
    "02-Apr-12"
    "03-Apr-12"
    "04-Apr-12"
    "04-Apr-12"
    "05-Apr-12"
    end
    I want to convert these to numeric data for further manipulation. To get rid of the hyphens I typed

    Code:
    replace date=subinstr(date,"-","",.)
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str9 date
    "01Apr12"
    
    ...output omitted
    
    "05Apr12"
    end

    I then used the following code:

    Code:
    gen numerical_date=date(date,"DMY")
    This produces missing values as follows:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float numerical_date
    .
    .
    .
    .
    .
    .
    .
    .
    .
    end

  • #2
    You need to specify a top year in your call to -date()-. See

    Code:
    help datetime
    e.g.

    Code:
    date(date, "DMY", 2050)

    Comment


    • #3
      Note that removing the hyphens is unnecessary. Starting from your sample data:
      Code:
      . generate date_n = date(date, "DMY", 2050)
      
      . format date_n %td
      
      . list, clean
      
                  date      date_n  
        1.   01-Apr-12   01apr2012  
        2.   01-Apr-12   01apr2012  
        3.   01-Apr-12   01apr2012  
        4.   02-Apr-12   02apr2012  
        5.   02-Apr-12   02apr2012  
        6.   03-Apr-12   03apr2012  
        7.   04-Apr-12   04apr2012  
        8.   04-Apr-12   04apr2012  
        9.   05-Apr-12   05apr2012
      Along with looking at help datetime as Nick recommends, before working with dates and times, any Stata user should thoroughly review the very detailed Chapter 24 (Working with dates and times) of the Stata User's Guide PDF. After that, the help datetime documentation will usually be enough to point the way. All Stata manuals are included as PDFs in the Stata installation (since version 11) and are accessible from within Stata - for example, through the PDF Documentation section of Stata's Help menu.

      Comment


      • #4
        Thanks Nick and William.

        The top date convention is new to me, so thank you for drawing it to my attention.

        Comment

        Working...
        X