A timelike extension of Fermat's principle in general relativity and applications