Solution (source code)

= Solution

Choose zero <potential energy> at the equilibrium position. For the <simple harmonic oscillator>, the <kinetic energy> and <elastic potential energy> give the <Lagrangian>
$$
L=T-V=\frac12m\dot x^2-\frac12kx^2.
$$
Its <canonical momentum> is $p=\partial L/\partial\dot x=m\dot x$. The <Legendre transform> defining the <Hamiltonian> consequently gives
$$
\boxed{H(x,p)=p\dot x-L=\frac{p^2}{2m}+\frac12kx^2=T+V.}
$$
The <Euler-Lagrange equation> is $m\ddot x+kx=0$. Thus along the motion
$$
\frac{dH}{dt}=m\dot x\ddot x+kx\dot x
=\dot x(m\ddot x+kx)=0.
$$
This proves <conservation of energy>. Equivalently, the <Lagrangian> has no explicit time dependence, so $dH/dt=-\partial L/\partial t=0$. The <Lagrangian> itself need not be constant: the <kinetic energy> and <potential energy> exchange periodically.