Los Angeles Superior Court Judge Keith Schwartz also told Redmond O'Neal to serve five years on probation and gave him a three-year suspended prison sentence, which would only be imposed if the younger O'Neal gets into trouble again.
O'Neal, 26, also pleaded no contest to being a felon in possession of a firearm when he was arrested Aug. 2 after a traffic stop.
He entered the pleas without an agreement with prosecutors, district attorney's spokeswoman Jane Robison said.
"The defense team appreciates that Judge Schwartz gave Redmond the help that he needs to turn his life around," attorneys Richard Pintal and Michael Brewer said in a statement. "The court recognized that drug rehabilitation is the best thing for Redmond and society as a whole."
Pintal said his client will be required to remain in a lockdown rehab facility and is facing a tough fight to beat his heroin addiction.
"It's especially insidious in that it's intensely physically addictive and coming off of, or ceasing in any respect; causes incredible physical pain," Pintal said.
Ryan O'Neal attended his son's sentencing, which was first reported by celebrity website RadarOnline.com.
Redmond O'Neal has had a string of drug-related arrests over the years. He had to be released from jail briefly to attend his mother's funeral when she died in June 2009.