The value of the transaction, still to be determined, is expected to be about €400 million.
Vattenfall has a 74.9 percent stake in the electricity grid company, Stromnetz Hamburg, while the remaining 25.1 percent belongs to the German city.
"The value of the entire electricity grid company has preliminarily been agreed at €550 million euros," the Swedish company said. "However, both parties have agreed on a minimum value of €495 million."
The transaction was a result of a popular initiative launched in 2010 by a pressure group which included environmentalists, consumer organisations, unions and local churches.
In a referendum held last September, 50.9 percent voted in favour, while the Social Democratic mayor and the Christian Democratic Union, Germany's largest party, had campaigned for a no-vote.
Vattenfall said it had agreed unwillingly to the deal.
"We regret to have to sell the electricity network business, but will continue to have a strong presence in the region and work closely as a partner to the city of Hamburg," said Tuomo Hatakka, head of Vattenfall's Continental Europe region.
It is not the first time that the Swedish company has faced difficulties in Germany, which became one of its major markets in 2010.
In March 2011, the city of Berlin announced the immediate closure of nuclear reactors at the Brunsbuettel and Kruemmel plants, co-owned by Vattenfall and German energy firm EON.
The referendum in Hamburg included an option to buy the local district heating company Vattenfall Waerme Hamburg in 2019, for a minimum price of €950 million or €1.15 billion if a gas-powered combined heat and power plant is built.
More than 200 power grids and water systems have been bought by local administrations in Germany since 2007, according to VKU, the German federation of local utilities.