Greetings! There are two main possibilities for the writing of this Psalm – either for the dedication of the site for the future temple (build by David’s son, Solomon) or after God stopped the plague He sent in response to David’s call for a census in 1 Chronicles 21.
A psalm. A song. For the dedication of the temple. Of David.
1 I will exalt you, O Lord,
for you lifted me out of the depths
and did not let my enemies gloat over me.
2 O Lord my God, I called to you for help
and you healed me.
3 O Lord, you brought me up from the grave;
you spared me from going down into the pit.
4 Sing to the Lord, you saints of his;
praise his holy name.
5 For his anger lasts only a moment,
but his favor lasts a lifetime;
weeping may remain for a night,
but rejoicing comes in the morning.
6 When I felt secure, I said,
“I will never be shaken.”
7 O Lord, when you favored me,
you made my mountain stand firm;
but when you hid your face,
I was dismayed.
8 To you, O Lord, I called;
to the Lord I cried for mercy:
9 “What gain is there in my destruction,
in my going down into the pit?
Will the dust praise you?
Will it proclaim your faithfulness?
10 Hear, O Lord, and be merciful to me;
O Lord, be my help.”
11 You turned my wailing into dancing;
you removed my sackcloth and clothed me with joy,
12 that my heart may sing to you and not be silent.
O Lord my God, I will give you thanks forever.
The Holy Bible : New International Version. 1996, c1984. Grand Rapids: Zondervan.
Verse 5 above reminds me of this passage in Hebrews. We don’t like to hear this, but God loves believers enough to discipline them. As the saying goes, He is more concerned about our holiness than our happiness. But we can trust that his favor and forgiveness for eternity.
Hebrews 12:5-11 And you have forgotten that word of encouragement that addresses you as sons: “My son, do not make light of the Lord’s discipline, and do not lose heart when he rebukes you, because the Lord disciplines those he loves, and he punishes everyone he accepts as a son.” Endure hardship as discipline; God is treating you as sons. For what son is not disciplined by his father? If you are not disciplined (and everyone undergoes discipline), then you are illegitimate children and not true sons. Moreover, we have all had human fathers who disciplined us and we respected them for it. How much more should we submit to the Father of our spirits and live! Our fathers disciplined us for a little while as they thought best; but God disciplines us for our good, that we may share in his holiness. No discipline seems pleasant at the time, but painful. Later on, however, it produces a harvest of righteousness and peace for those who have been trained by it.