Announcement

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

  • Extracting last 4 digits of string

    I'm looking to extract the last four digits of a date formated as 07apr2021 to create a new variable, so right now i'm using

    gen year=substr(fiscal_year_ended,-4,.)

    which I think would work if I had only numerical/string values, but with a combination of both I'm for sure confusing the system. So I have since tried
    gen year= (substr(string(fiscal_year_ended),-4,.)) but now I'm getting numbers that are not even prevalent in my data set. Advice?

  • #2
    If your variable is a numeric daily date then it's an integer so substr() does not apply and even if you force the date to a string the last 4 characters are no use.

    A numeric daily date usually has a display format as you cite but that doesn't make it a string.

    Here's today's date. It is an integer on a scale on which 1 January 1960 was 0.

    Code:
    . di mdy(4, 7, 2021)
    22377
    That's convenient for calculations but useless for most human purposes, hence the ability to see a display format not just an integer: .

    Code:
    di %td mdy(4, 7, 2021)
    07apr2021
    If I want to see or get the year out of a daily date then there is a function for the purpose:

    Code:
    . di year(mdy(4, 7, 2021))
    2021
    Here di means display and is Stata's calculator command, among other things.

    The last 4 characters of today's date are to Stata 2377 which is definitely not what you want.

    At some point you'll need to look at help datetime !!!

    Comment


    • #3
      Cross-posted at https://www.reddit.com/r/stata/comme...from_a_string/

      Katrina: Please see our cross-posting policy, which is explicit at https://www.statalist.org/forums/help#crossposting

      I've often seen comments in forums that cross-posting in different forums without explaining the fact is rude and disrespectful, signalling that you don't care about duplicated effort. I wouldn't go that far, but as said the view exists.

      Let's phrase this positively:

      1. If people think they have an answer, they can look at the other site to see if an answer as good or better has already been posted and bail out if so.

      2. If people want to know the answer too, they can look at the other site to see if an answer has been posted.

      3. If you get a good answer in one place and not the other, you can post a reference or a summary of the answer, and then it's on record. For example, the thread title here is precise and informative and could easily look relevant to others.

      Not explaining cross-posting implies that all relevant people are scanning all relevant forums, so that they don't need to be told about cross-posting. But that's empirically not correct. It's also inconsistent, as if all relevant people are scanning all relevant forums, you need only post in one of them.

      Comment

      Working...
      X