I took data from the [Tennis ATP][1] and [Tennis WTA][2] repositories in GitHub. They do not have all the rankings, so it is not comprehensive and [Logan's answer][3] will be more accurate.

From there we see that:

- 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.

  [1]: https://github.com/JeffSackmann/tennis_atp
  [2]: https://github.com/JeffSackmann/tennis_wta
  [3]: https://sports.stackexchange.com/a/16732/11439