We don’t know exactly when David first wrote and sang this song. At the start of both records of the song, the Bible tells us only that:
David sang this song to the Lord on the day the Lord rescued him from all his enemies and from Saul.
Logic suggests it would have been not long after David took the throne and defeated the nations around him that had tried to defeat him before he could get too established. It follows on well from David’s victories against the four enemy nations.
David’s references to his innocence, keeping himself from sin and being blameless before God suggest the wrote the song before the murder of Uriah to cover up his sin with Bathsheba, the rebellion by Absalom, and before his later census of Israel.
Alternatively, if it was written towards the end of David’s reign, as its current place in the text of 2 Samuel suggests, it shows a far greater understanding of God’s grace and forgiveness of sin than most of us will ever have.
One view is that the song was written and sung when David was younger, but also when he was older and looking back over his life with some gratitude. Charles Spurgeon had some interesting commentary on this Psalm.