(copypasta)
The answer is 'whenever you feel like it'. And immediately after so.
And always do it directly! With a yes/no response, and accept whatever she says. This is where guys mess up a lot.
They either do it indirectly (creepy) way like "hey i'm going to blah this weekend you can come if you want". This is bad because your intentions are not clear. Are you just friends? Is this a date? Will others be there? Do you normally do this?
Remember: ambiguity = creepy. Be direct and shameless.
The other half is the yes/no response. Some guys reaaaaaly want the girl to say yes. They want it so badly, that they'll pout like a little boy if she says no. She will feel this pressure. If you pressure her like this, then it's not a question anymore, it's a command. It's just super immature. So you just need to prepare yourself for both the yes and the no, and handle each with compassion.
So how do you do it? And when?
The MOMENT you feel it in your heart. Even if you never spoke to her, or if you known her for years, don't hide it and don't feel shame.
A girl you just met:
"Hi my name is user, what's your name?"
"Anonette"
"Anonette would you like to go out with me?"
This is very good because it's direct, she knows exactly what you're asking and why you're doing it. There's no ambiguity. Also you gave her the full choice (and no pressure) to say no. Or to say yes. You really laid the choice on her. Girls like feeling this. Even if she says no, you'll have made her day because she'll feel validated because a guy asked her out.
A girl you've know for a while:
You can say something relevant or personalized, fine. But when it comes the moment, it's very quick:
"Would you like to go out with me?"
"What, like out on a date?"
"Like out on a date."
"I... didn't expect this..."
"So is that a no?"
"Of course I want to go out with you!"
In this case, if she instead doesn't give you a yes/no, you have the right to remind her "Indecision is a decision, too."