No fixed rule, you could apply for the 30 day extension just after entering Thailand, but some immigration offices might refuse to give you the extension then and tell you to come back when it's closer to expiry, no idea why they do it though...
I would recommend to just go in the last one or two weeks, then you shouldn't have a problem. If it's important for you to know tell the people here which immigration office you will attend, maybe somebody can share their experience with this specific office.