The belief that the third time something is attempted is more likely to succeed than the previous two attempts. It is also used as a good luck charm - spoken just before trying something for the third time.
The first time we come across what appears to be a precursor to this phrase is in Elizabeth Barrett Browning's Letters addressed to R. H. Horne, 1839:
‘The luck of the third adventure’ is proverbial.
It is listed explicitly in Alexander Hislop's The proverbs of Scotland, 1862:
"The third time's lucky. "
The 'proverbial' description from the mid 19th century suggest it dates from earlier, although how much earlier we can't really tell.
Why is the third time lucky? Again, we don't know. There are a few suggestions. The most common is that it alludes to the belief that, under English law, anyone who survived three attempts at hanging would be set free. This is probably from the story of John 'Babbacombe' Lee. Lee was a West Country sailor who was convicted of the murder of Emma Keyse at Babbacombe Bay in 1885. He was sentenced to hang at Exeter prison and three attempts to execute him all failed. The Home Secretary of the time, Sir William Harcourt, commuted the sentence to life imprisonment and Lee was later freed. He was known thereafter as 'the man they couldn't hang' and went on to live a long life, dying sometime in the 1940s. Fascinating story though it is, the use of 'third time lucky' predates it and thus it can't be the origin. Nor is any earlier reference to the supposed English law on freeing those who survived three hanging attempts. This legal ruling never existed in any general sense and is restricted to isolated cases like Lee's.
Another suggestion is that it refers to the Christian Trinity. There seems little to support that idea. It might relate in some way to goodness or luck being associated with the number three, but has no specific link with the third of anything.
It seems more likely that it is just a folk belief that, having had setbacks, we ought to persevere and not give up. This is enshrined in the phrase 'try, try and try again'. Three seems to be the right number of times to try. Two isn't enough but four is too many. Think of every time you've seen a drama in which a character tries to unlock a door with an set of unfamiliar keys. The first key fails, the second key fails - it is always the third that works.
The same idea is expressed in the American expression 'third time's a charm'. This may be an variant of the earlier 'third time lucky' or it may have arisen independently in the USA. The first citation I can find for it is in The Weekly Sentinel, June 1912. This is in a rather snooty court report about a Mrs. Martha Carliss, who had been twice married previously and 'gave her name as' sixty four:
That Mrs. Martha Carliss evidently believes in peace and happiness in wedlock and that she probably thinks third time's a charm is shown by the fact that she was granted a license today to marry Andrew W. Mowery.