Announcement

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

  • Create month variable from a date

    Hello, I have a dataset with a date variable in the storage type 'str11', like this one 11-MAY-2022. How can I create a new variable with just the month (in this case, 'MAY')? Thank you in advance

  • #2
    Luca:
    welcome to ths forum.
    You may want to consider:
    Code:
    . set obs 1
    Number of observations (_N) was 0, now 1.
    
    . g old_date="11-MAY-2022"
    
    . split old_date,p(-)
    variables created as string: 
    old_date1  old_date2  old_date3
    
    . keep old_date old_date2
    
    . list
    
         +------------------------+
         |    old_date   old_da~2 |
         |------------------------|
      1. | 11-MAY-2022        MAY |
         +------------------------+
    
    .
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      Did you try finding out from

      Code:
      help datetime
      as sooner or later you should be reading that?

      If that is really what you want it is probably

      Code:
      gen month_name = substr(date, 4, 3)
      but that won't be much use for analysis. For most serious Stata purposes one or more of these variables will be more use.

      Code:
      clear
      set obs 1
      gen date = "11-MAY-2022"
      
      gen ddate = daily(date, "DMY")
      format ddate %td
      
      gen mdate = mofd(ddate)
      format mdate %tm
      
      gen month = month(ddate)
      
      list
      
      
          +------------------------------------------+
           |        date       ddate    mdate   month |
           |------------------------------------------|
        1. | 11-MAY-2022   11may2022   2022m5       5 |
           +------------------------------------------+

      Comment

      Working...
      X