Announcement

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

  • Extracting a date variable

    I have a date variable that is stored like this "06-FEB-2021 16:55". Any suggestions on how to use "clock" to extract this given the month is upper case "FEB" "JAN" etc. I wrote some code to do this but it isn't very efficient.

  • #2
    Here is the clunky code I wrote:
    gen day = substr(datetime,1,2)
    destring day, replace
    gen month = substr(datetime,4,3)
    replace month="1" if month=="JAN"
    replace month="2" if month=="FEB"
    replace month="3" if month=="MAR"
    replace month="4" if month=="APR"
    replace month="5" if month=="MAY"
    replace month="6" if month=="JUN"
    replace month="7" if month=="JUL"
    replace month="8" if month=="AUG"
    replace month="9" if month=="SEP"
    replace month="10" if month=="OCT"
    replace month="11" if month=="NOV"
    replace month="12" if month=="DEC"
    destring month, replace
    gen year = substr(datetime,8,4)
    destring year, replace

    Comment


    • #3
      Code:
      display %td dofc(clock("06-FEB-2021 16:55", "DMYhm"))
      Res.:

      Code:
      . display %td dofc(clock("06-FEB-2021 16:55", "DMYhm"))
      06feb2021
      See

      Code:
      help dofc()

      Comment


      • #4
        Thank you! This is much more efficient.

        Comment


        • #5
          Here is another way to do it.

          Code:
          di %td daily(word("06-FEB-2021 16:55", 1), "DMY")
          06feb2021
          with the implication


          Code:
          gen ddate = daily(word(yourvar, 1), "DMY")
          The upper case months such as JAN are fine for Stata's date-time functions.

          Comment

          Working...
          X