Dynamical invariants for time-dependent real and complex Hamiltonian systems