The psalm was written by David when the Philistines had seized him in Gath. Although the time and related passage (chapter and verses were added centuries later) are not listed in the title, it can be assumed to be between when David fleed King Saul and eventually became king of Judah and later all of Israel.
The passage documenting David’s initial fleeing King Saul in 1 Samuel 21:10-22:2 is the most probable because that is when he was most vulnerable. Also, later when men had begun following David, he found sanctuary with Achish, the king of Gath, and perhaps became a vassal of the Philistines (1 Samuel 27:1-7). Eventually when he was king David defeated the Philistines and made Gath an Israelite town (1 Chronicles 18:1)
David’s life had suddenly changed for the worse. He was alone and captured. Men from Saul were hotly pursuing him—all day, every day. He had no place to lay his head and no safety to sleep very long. He was hungry, cold, hot, and dirty. Pride and envy fueled his enemies. His friends deserted him. His family was not safe with him.
David sought the mercy of God. He appealed to God’s character of care for the needs of his children. As the Lord said through the prophet Jeremiah, “Return, faithless Israel. I will frown on you no longer, for I am merciful. I will not be angry forever.” (Jeremiah 3:12)