The time-dependent $CP$ asymmetries of $B^0to pi^+pi^-$ and $B^0_mathrm{s}!to K^+K^-$ decays are measured using a data sample of $pp$ collisions corresponding to an integrated luminosity of 1.9 fb$^{-1}$, collected with the LHCb detector at a centre-of-mass energy of 13 TeV. The results are begin{eqnarray*} C_{pipi} & = & -0.311 pm 0.045 pm 0.015, S_{pipi} & = & -0.706 pm 0.042 pm 0.013, C_{KK} & = & phantom{-}0.164 pm 0.034 pm 0.014, S_{KK} & = & phantom{-}0.123 pm 0.034 pm 0.015, cal {A}^{mathrm{DeltaGamma}}_{mathit{KK}} & = & -0.83phantom{0} pm 0.05phantom{0} pm 0.09, end{eqnarray*} where the first uncertainties are statistical and the second systematic. The same data sample is used to measure the time-integrated $CP$ asymmetries of $B^0to K^+pi^-$ and $B^0_mathrm{s}to K^-pi^+$ decays and the results are begin{eqnarray*} A_{CP}^{B^0} & = & -0.0824 pm 0.0033 pm 0.0033, A_{CP}^{B^0_mathrm{s}} & = & phantom{-}0.236phantom{0} pm 0.013phantom{0} pm 0.011. end{eqnarray*} All results are consistent with earlier measurements. A combination of LHCb measurements provides the first observation of time-dependent $CP$ violation in $B^0_mathrm{s}$ decays.