Announcement

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

  • extract year from date variable

    I have a date variable in string format and want to extract only the year. Below is mye date variable

    "11-05-2017 09:25:32"
    "18-05-2017 13:28:45"

    I have tried using the substring function but it is somewhat difficult to understand how this works.

  • #2
    I made it work using this command:


    Comment


    • #3
      For the sake of future reference:
      From Stata's understanding, you don't have a date variable, but a string. This string variable contains time stamps. Each time stamp can be shortened to a date, which can be shortened to a year. The most Stata-ish way, from my personal view, to achieve this is by converting the string to a Stata time/date format, and years from this, as presented in the following minimal example:
      Code:
      clear
      input str19(timestamp)
      "11-05-2017 09:25:32"
      "18-05-2017 13:28:45"
      end
      
      // create time variable from string (just for demonstration purposes)
      generate double time=Clock(timestamp,"DMY hms")
      format time %tC
      
      // create date variable from string
      generate double date=date(timestamp,"DMY hms")
      format date %td
      
      // etract year from time variable
      generate year=year(date)
      
      // see result
      list
      See -help datetime- and all the connected functions in -help datetime_functions- for details.

      However, in this special example, you also simply could extract the characters 7 through 10 from your string, convert them to a number, and you are set:
      Code:
      clear
      input str19(timestamp)
      "11-05-2017 09:25:32"
      "18-05-2017 13:28:45"
      end
      
      // create yearvariable as substring from string source
      generate year=real(substr(timestamp,7,4))
      list
      Kind regards
      Bela
      Last edited by Daniel Bela; 27 Nov 2017, 03:48.

      Comment

      Working...
      X