Madrid is known for its scorching hot summers and freezing winters and while there’s often some exaggeration, you might want to avoid the hottest months, July and August, when temperatures hit around 40 degrees, potentially making sightseeing quite laborious.
Both Spring (March to May) and Autumn (September to November) are generally considered good times to visit, when you can expect warm days and cooler nights.
June’s warm evenings mean it’s the best time to experience the city’s party vibe, while the drop in rates during the winter mean it’s still a good time to visit if you don't mind cold winds and the occasional bit of snow.