A stopping time $T$ is the first time when a trajectory of a stochastic process satisfies a specific criterion. In this paper, we use martingale theory to derive the integral fluctuation relation $langle e^{-S_{rm tot}(T)}rangle=1$ for the stochastic entropy production $S_{rm tot}$ in a stationary physical system at stochastic stopping times $T$. This fluctuation relation implies the law $langle S_{rm tot}(T)ranglegeq 0$, which states that it is not possible to reduce entropy on average, even by stopping a stochastic process at a stopping time, and which we call the second law of thermodynamics at stopping times. This law implies bounds on the average amount of heat and work a system can extract from its environment when stopped at a random time. Furthermore, the integral fluctuation relation implies that certain fluctuations of entropy production are universal or are bounded by universal functions. These universal properties descend from the integral fluctuation relation by selecting appropriate stopping times: for example, when $T$ is a first-passage time for entropy production, then we obtain a bound on the statistics of negative records of entropy production. We illustrate these results on simple models of nonequilibrium systems described by Langevin equations and reveal two interesting phenomena. First, we demonstrate that isothermal mesoscopic systems can extract on average heat from their environment when stopped at a cleverly chosen moment and the second law at stopping times provides a bound on the average extracted heat. Second, we demonstrate that the average efficiency at stopping times of an autonomous stochastic heat engines, such as Feymanns ratchet, can be larger than the Carnot efficiency and the second law of thermodynamics at stopping times provides a bound on the average efficiency at stopping times.