Announcement

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

  • Transforming dates in numerical variables

    Hello,

    I have a date string variable in the following format "Jan-01" (month-year). I would like this variable to be numerical. Can anyone help?

    Thank you

  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str10 date
    "Jan-01"
    "Feb-99"
    end
     
    gen wanted= mofd(daily(date+"-01", "MYD", 2023))
    format wanted %tm
    Res.:

    Code:
    . l
    
         +-----------------+
         |   date   wanted |
         |-----------------|
      1. | Jan-01   2001m1 |
      2. | Feb-99   1999m2 |
         +-----------------+

    Comment


    • #3
      Almost all of what you need to know about dates (and times) is documented within

      Code:
      help datetime
      Here the function monthly() does what you want. For individual dates, consider

      Code:
      . di monthly("Jan-01", "MY", 2025)
      492
      
      . di %tm monthly("Jan-01", "MY", 2025)
       2001m1
      where 2025 is an upper limit on the year. If you need a different upper limit, you know what to do. If your data include e.g. monthly dates for July 1923 and July 2023, you're stuck.

      You didn't give a data example in the sense of dataex (FAQ Advice #12). But a guess at what you want is

      Code:
      gen wanted = monthly(bad_date, "MY", 2025)
      which you need to tweak according to actual and desired variable names.

      Comment


      • #4
        Thank you, Andrew and Nick. Your support is really helpful.

        Comment

        Working...
        X