From my understanding, there are two ways that they know this. The first is that they have people fill out forms about what they watched. It's like keeping a manual record of your TV habits. The second is by having some kind of box attached to the TVs; the box keeps track of that same information automatically.
Both methods are only used for small select groups of people, so the ratings do not truly reflect reality. For instance, a while back I read a
report a about Neilsen claims about game console usage. Their claims put Wii usage very low, based on 17,000 US households. Neilsen didn't report that 17,000 was less than 0.2% of Wiis sold in the US by the period of their report.