Thunderstorms can happen at night because they form differently than daytime thunderstorms.
Instead of relying on the sun to heat the ground, nighttime thunderstorms, or "elevated" thunderstorms, form higher up in the atmosphere. According to research, this happens "in the absence of heating at the ground by the sun." They develop above cooler air near the ground, which is different from daytime storms that are triggered by warm air rising from the surface. In other words, during the day, the sun warms the surface, creating rising warm air that fuels storms. At night, that surface heating is gone, so any storms must find their energy elsewhere, higher in the atmosphere.