Madrid is located in the heart of Spain, and its continental climate is characterized by low precipitation, dry hot summers and temperate winters. When planning to visit Madrid, you should decide if you can tolerate dry heat, and if yes, then almost any time is a good time.
Spring (April, May) and early fall (September, October) are usually the best choices, since daylight hours are long, days are warm, nights are cool, and the weather is conducive to long walks and city exploration. Most sights are already/still open late. In winter, the temperature during the day drops to +9-10В°C, and at night it can get as cold as +2В°C, so even though you are headed to Spain, pack some warm clothes.
Despite the common advice of avoiding southern cities in summer due to the heat, summer in Madrid may be a good idea, especially if you can go in June, when the heat is still moderate (+28В°C), and all museums, galleries, restaurants are open long hours. In July and August the temperature can reach up to +40В°C, and even though the low humidity makes it bearable, travellers who are heat-sensitive should consider a cooler alternative.
It is worth noting that Spaniards still like to close their businesses and head somewhere for a vacation in August, but it is less common now than it once was. You are likely to encounter a few closed cafГ©s and restaurants, but don't let it stop you from heading to Madrid when you want, there are still plenty activities and places to visit!