The Earth was created 4.54 billion years ago when part of the Sun's accretion disc agglomerated into a spherical body. At that time, shortly after the birth of the Sun itself, the solar system's matter was much more scattered around, in the form of asteroids and dust rather than planets. This "matter cloud" has been called a Bok globule, and these globules have been observed in other parts of the Galaxy. Scientists have determined the age of the Earth relatively precisely using isotope dating of the world's oldest rocks.
It is not known precisely what mechanism caused the precursor of the solar system, a gaseous nebulae, to form into the Sun and its attendant accretion disc. It may have been shockwaves from a nearby supernova, or simple gravitational collapse due to a threshold density. Whatever the cause, when enough density gathered in the center of the gas cloud, it ignited to become the Sun. The resulting heat banished volatiles (materials with low melting points) to the outer solar system, while leaving rocky bodies, like the Earth, Mercury, Venus, and Mars, in the inner solar system, where they could grow.
The early creation of the Earth was not so smooth, a series of events characterized by massive impacts. Due to energy leftover from the gravitational collapse that formed the Earth, the surface would have initially been a magma ocean until it slowly cooled down. Shortly after the formation of the Earth, the planet was impacted by a Mars-sized body called Theia which formed in a Lagrange point (point of gravitational equilibrium) in the Earth's orbit but not at the exact same place. Over a period of time, orbital oscillations caused Theia to impact the Earth, ejecting many gigatons of material which agglomerated to form the Moon.
After the formation of the Moon, which also had a magma ocean for millions of years, both the Earth and the Moon were heavily bombarded by asteroids and comets in a series of events known as the Late Heavy Bombardment. This extensive bombardment helped deliver volatiles, like water, to the Earth's surface, and played a role in the creation of the oceans. Most of the craters on the Moon today were formed during this heavy bombardment.