When fasting in Ramadan was first prescribed, people would not approach their wives for the whole of Ramadan, and some men were being unfaithful to themselves. So Allah revealed, "Allah knows that you were deceiving yourselves, so He has turned to you in forgiveness and pardoned you" [Baqarah 2:187].
لما نزل صوم رمضان كانوا لا يقربون النساء رمضان كله، وكان رجال يخونون أنفسهم، فأنزل الله: {علم الله أنكم كنتم تختانون أنفسكم فتاب عليكم وعفا عنكم}.
Bukhari related it in the chapter on tafsir (4508), via Abu Ishaq Sabi, from Bara bin Azib.Ibn Hajar said in Fath al-Bari (8/181–182), "The apparent wording of the hadith in this chapter indicates that intercourse was forbidden throughout the entire night and day, unlike eating and drinking, which were permitted at night as long as sleep had not occurred. However, the rest of the hadiths transmitted on this subject indicate that there is no such distinction, as I will mention afterward. So his statement, 'They would not approach women,' should be understood as referring to what was generally the case, in order to reconcile the reports."