MADRID — Spain’s government and main labor unions agreed on Thursday to raise the retirement age as part of an overhaul of the country’s pensions system, averting threatened organized protests and responding to investors who have been demanding that Spain clean up its public finances.

After a year of negotiations, the draft deal ensures that Spain’s normal retirement age will rise to 67 from 65. As part of a compromise, however, the government agreed that workers could retire at 65 if they had contributed to the state pensions system for at least 38.5 years. The agreement is also intended to cut the cost of future pension payments by basing the calculation for such payments on a worker’s last 25 years of earnings, rather than the 15 years under current law.

Under pressure from investors to speed up structural reforms to the economy, José Luis Rodríguez Zapatero, Spain’s prime minister, had set Friday as a deadline to reach agreement on changing the pension system. He had insisted that the government would in any case impose such an overhaul by decree if no deal had been reached by that date.

Union leaders, however, had warned that they would call the country’s second general strike in less than six months if the government changed the pension system without their backing.