Petro, a former member of the M-19 guerrilla movement who has vowed profound economic and social change, had 40.3 per cent of votes, national registry office tallies showed on Sunday, with 96.2 per cent of ballot boxes counted.
Hernandez, the septuagenarian former mayor of Bucaramanga, won 28.1 per cent.
Petro, a 62-year-old former mayor of Bogota, had consistently led opinion polls on promises to redistribute pensions, offer free public university and battle deep inequality.
He has promised to fully implement a 2016 peace deal with the FARC rebels and seek peace talks with the still-active ELN rebels, as well as halt all new oil and gas development.
Youth are a major demographic for Petro, who had about 50 per cent support in opinion polls from the country's youngest voters.
Hernandez rose in the polls only in the last two weeks, boosted by his colourful social media presence and anti-corruption promises.
He has promised to end privileges for officials and govern with austerity.
Despite Hernandez's anti-corruption rhetoric, he is facing an investigation over allegations he intervened in a rubbish collection tender when he was mayor of Bucaramanga to benefit a company his son had lobbied for.
Hernandez denies the accusations and insists they are designed to derail his bid or the presidency.
Hernandez, who is financing his own campaign, has relied heavily on social media, posting eccentric videos on TikTok, including one of him riding an electric scooter.