I took data from the Tennis ATP and Tennis WTA repositories in GitHub. They do not have all the rankings, so it is not comprehensive and Logan's answer will be more accurate.
From there we see that:
- (this is to be changed) Rafa Nadal was 1st on 18 August 2008 for the first time and hist last week on that position was on 21 August 2017. This makes it 9 years and 3 days.
- Andre Agassi was 1st on 10 April 1995 for the first time and his last week on that position was on 1 September 2003 (100 weeks all together). This makes it 8 years and 5 months.
- Roger Federer was 1st on 2 Feb 2004 for the first time and the last time was on 29 Feb 2012 (for a total of 297 weeks all together). This makes it more than 8 years.
In women:
- Serena Williams started on 8 July 2002 and her last was on 9 September 2016, for a total of 14 years and 3 months. 308 in total.
- Steffi Graff started on 17 August 1987 and her last was on 24 March 1997, for a total of 9 years and 7 months. 383 weeks in total.