I have been asking myself this question constantly because I am not the most limber person in the world. One day, that question was answered. I have no idea when that day really was but these last 6 months I have found my way of stretching as well as when and for how long.
The first question you should ask yourself is, what do I want from stretching? What is my final end goal with it? For me, it's being able to fold over with my hands past my toes, also known as a forward fold. From there, what is the main muscle preventing you from doing that? That takes a while to figure out, for me, it's my glutes. I have spent the majority of my time working on a 90 / 90 stretch as my main stretch whenever I do have a session.
When? My best time is before bed or using stretching with light pump work as more of an active recovery session versus just stretching. I found this to be better as I could get into a position quicker which pointed to a lot of markers like " am I doing the right stretch?". Always do checks and balances of your sessions. Does this thing help this thing? No? Why? Do I even need it to or do I want something else out of it? Some stretches should be for enjoyment otherwise you won't keep doing it. Find a stretch you know you can do well, for me it is a knee to chest lying down.
How long? Short to long sessions is what worked for me. Do just a little to feel it, stop. Repeating this process you will see you can get into a better position at a faster rate which will actually mean you do not need as much ( depends on goals).
Find a way to look at stretching as an accessory to lifting, such as the range of motion to perform a lift. Or, look at it as its own thing and program it like you would a lifting session.