Datolo leveled in the 64th minute when he pounced after keeper Gianluigi Buffon could only parry a header from German Denis and the rebound fell in his path.
Hamsik snatched the winner 10 minutes from time from Datolo's cross to give coach Walter Mazzarri a record of three wins in four league games since replacing the sacked Roberto Donadoni.
Sebastian Giovinco doubled the lead in the 54th minute after a mistake by Napoli defender Matteo Contini, but Marek Hamsik pulled a goal back five minutes later with his seventh of the season from Jesus Datolo's low cross.