Why was St Petersburg the capital of Russia between 1712 to 1918?

Why was St Petersburg the capital of Russia between 1712 to 1918 (with the exception of a few years under Peter II) ? Why did Moscow become the capital in 1918?
Update: Thank you all for your answers!
5 answers 5