The forty day tradition following childbirth is quite ancient. It is part of the Mosaic Law, the Law of Moses, and appears in the Old Testament in the Bible. Without a doubt the ancient Hebrews and other people of the Middle East practiced this tradition, including in Anatolia, modern day Turkey.
Either because of Jewish tradition or becuase the Spanish Christians were adhering to the fact that for 40 days after Jesus was born, Mary was considered unclean according to Mosaic Law. After the 40 days were over, both the mother and child were purified. Here's the Biblical verse:
Luke 2
:22-24