Tratnik beat O'Connor at the end of the hilly 229 kilometre route from Udine to San Daniele del Friuli on Wednesday (AEDT).
Neither of them had ever won a stage in a grand tour and both entered the final kilometre together.
However, it was Tratnik who crossed the line first, with his arms outstretched and tears streaming down his face.
O'Connor thumped the handlebars in frustration.
Enrico Battaglin was third, 1:14 behind his Bahrain-McLaren teammate Tratnik.
All three were part of a large breakaway of 30 riders, who escaped early in the stage, on the first of six classified climbs.
Almeida led the group of overall favourites across, nearly 13 minutes after Tratnik, and increased his lead slightly after attacking in the final two kilometres.
The Portuguese rider, who rides for the Deceuninck-Quick Step team, moved to 17 seconds ahead of Wilco Kelderman.
Jai Hindley was third, 2:58 behind Almeida.
Colombian sprinter Fernando Gaviria withdrew from the race before the start of the stage after becoming the latest cyclist to test positive for the coronavirus.
Thursday's 17th stage is a mountainous 203km leg from Bassano del Grappo to Madonna di Campiglio.
The route features four classified climbs, three of which are the highest category.
The race was rescheduled from its usual May slot because of the coronavirus pandemic.
The Giro ends on Monday with an individual time trial in Milan.