كتاب القدر
46  
The Book of Destiny
(1)
Chapter: How The Human Being Is Created, In His Mother's Womb, And His Provision, Lifespan And Deeds Are Written Down, And His Misery and Happiness
(1)
بَاب كَيْفِيَّةِ خَلْقِ الْآدَمِيِّ فِي بَطْنِ أُمِّهِ وَكِتَابَةِ رِزْقِهِ وَأَجَلِهِ وَعَمَلِهِ وَشَقَاوَتِهِ وَسَعَادَتِهِ
Sahih Muslim 2644

Hudhaifa b. Usaid reported directly from Allah's Messenger (ﷺ) that he said:

When the drop of (semen) remains in the womb for forty or forty five nights, the angel comes and says: My Lord, will he be good or evil? And both these things would be written. Then the angel says: My Lord, would he be male or female? And both these things are written. And his deeds and actions, his death, his livelihood; these are also recorded. Then his document of destiny is rolled and there is no addition to nor subtraction from it.
حَدَّثَنَا مُحَمَّدُ بْنُ عَبْدِ اللَّهِ بْنِ نُمَيْرٍ، وَزُهَيْرُ بْنُ حَرْبٍ، - وَاللَّفْظُ لاِبْنِ نُمَيْرٍ - قَالاَ حَدَّثَنَا سُفْيَانُ بْنُ عُيَيْنَةَ، عَنْ عَمْرِو بْنِ دِينَارٍ، عَنْ أَبِي الطُّفَيْلِ، عَنْ حُذَيْفَةَ بْنِ أَسِيدٍ، يَبْلُغُ بِهِ النَّبِيَّ صلى الله عليه وسلم قَالَ ‏ "‏ يَدْخُلُ الْمَلَكُ عَلَى النُّطْفَةِ بَعْدَ مَا تَسْتَقِرُّ فِي الرَّحِمِ بِأَرْبَعِينَ أَوْ خَمْسَةٍ وَأَرْبَعِينَ لَيْلَةً فَيَقُولُ يَا رَبِّ أَشَقِيٌّ أَوْ سَعِيدٌ فَيُكْتَبَانِ فَيَقُولُ أَىْ رَبِّ أَذَكَرٌ أَوْ أُنْثَى فَيُكْتَبَانِ وَيُكْتَبُ عَمَلُهُ وَأَثَرُهُ وَأَجَلُهُ وَرِزْقُهُ ثُمَّ تُطْوَى الصُّحُفُ فَلاَ يُزَادُ فِيهَا وَلاَ يُنْقَصُ ‏"‏ ‏.‏
Reference : Sahih Muslim 2644
In-book reference : Book 46, Hadith 3
USC-MSA web (English) reference : Book 33, Hadith 6392
  (deprecated numbering scheme)