Announcement

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

  • Get date from "YYYYMM" string

    I have a date variable that is a string in the form "200201" or 201004" ie four digits of year and then two digits of month. How can I create a date variable from that?

  • #2
    Please supply a data example as requested in FAQ Advice #12. Here are two solutions in a reproducible example. You only need one.


    Code:
    clear 
    input str6 awkward 
    "200201" 
    "201004"
    end 
    
    gen wanted1 = monthly(substr(awkward, 1, 4) + " " + substr(awkward, -2, 2), "YM") 
    
    gen wanted2 = real(awkward)
    replace wanted2 = ym(floor(wanted2/100), mod(wanted2, 100))
    
    format wanted? %tm 
    
    list
    See https://www.stata-journal.com/articl...article=dm0096 for a much fuller discussion.

    Comment


    • #3
      Thank you!

      Comment


      • #4
        Here is another way to do it with numdate from SSC. See https://www.statalist.org/forums/for...date-variables for much more detail.

        Code:
        . clear
        
        . set obs 2
        Number of observations (_N) was 0, now 2.
        
        . gen awkward = word("200201 201004", _n)
        
        . l
        
             +---------+
             | awkward |
             |---------|
          1. |  200201 |
          2. |  201004 |
             +---------+
        
        . numdate tm wanted = awkward, pattern(YM)
        
        . l
        
             +------------------+
             | awkward   wanted |
             |------------------|
          1. |  200201   2002m1 |
          2. |  201004   2010m4 |
             +------------------+

        Comment

        Working...
        X