For how long can one hold a soldering iron on a component pin when soldering?
Like everything in engineering... IT DEPENDS

Time, by itself, is meaningless. There are a few competing concerns:

The temperature must reach the melting point of the solder material. This depends on the type of solder, the parts (mass and chemical composition), the soldering iron tip material and shape, power applied to the tip and its thermal conversion efficiency, and the ambient temperature (ex. preheaters). 

It's not just about temperature, but how quickly you get there. If temperature rise is too slow, the total energy transferred past the pin to the internal part may be sufficient to damage or derate it. That is why all components come with either a JEDEC/IPC reference profile and/or a soldering temperature profile. This profile is an energy chart showing temperature vs. time.

If you ramp the temperature up too quickly you can get thermal fracturing of the part as the different elements inside expand at different rates breaking free of the ultrasonic bonding or lead frame.

If you leave the iron in contact for way too long you will overheat the part resulting in the destruction of the packaging (plastics don't fair so well, ceramics do much better) and the functional loss of the silicon die inside. There are many failure scenarios for microchips from overheating ranging from the obvious burn-out (physical fault) to the loss of function from ion-migration in the doped-semiconductors.

...but 2 seconds is a good average

The reason you hear 2-3 seconds as a "rule" is that for most parts and most irons and most situations and most PCB's and most... this time value works out safely.