The city attorney wants access to four years' worth of data about driver practices and the areas they serve.
Dennis Herrera said he wanted to ensure they were complying with local laws on safety, accessibility and not creating "a public nuisance".
Uber and Lyft have 15 days to comply or face charges of contempt and other court-imposed penalties.
Mr Herrera has also made a public records request to the state regulator, the California Public Utilities Commission (CPUC), for the same information.
Both companies are obliged to file annual reports with the CPUC, but they have argued successfully for that data to be kept confidential for competitive reasons.
"No-one disputes the convenience of the ride-hailing industry," Mr Herrera said.
"But that convenience evaporates when you're stuck in traffic behind a double-parked Uber or Lyft, or when you can't get a ride because the vehicle isn't accessible."
The algorithms used by the ride-hailing software also favoured some parts of the city over others, he added.
"In San Francisco, nearly 30% of rides take place in underserved neighbourhoods and 20% of Lyft rides begin or end at a public transit station," Lyft spokeswoman Chelsea Harrison said in a statement.
Uber spokeswoman Eva Behrend said that the company was "more than happy to work with the city to address congestion" but "a comprehensive solution" was needed.
Uber is already involved in a legal battle with San Francisco officials, over demands that the ride-hailing company shares its drivers' names and addresses.
Having shared them under protest in the past, Uber now maintains that doing so is an invasion of driver privacy.
Ride-hailing companies Uber and Lyft have been ordered to hand over details about their San Francisco operations.