Optimal nonequilibrium thermometry in finite time