Invalid value is recorded when user lands on page but don't do any activity like click or something. Adobe records time by calculating time between two events like when user enters page and click on something.
Time spent per visit = Last hit time - First hit time
if no hits/events generated after user visits the page then adobe would show "invalid" value for such cases.
Best way would be to filter out such value when you generate report instead of implementing any custom script.