I’m building a generic custom strToDatetime(string) function. The date string may be in some different formats. The 2 most popular alternatives seem datetime.strptime(string, format) and dateutil.parser(string). It seems datetime.strptime() requires a format and dateutil.parser() does not, so the possible solutions seem to be:
- Test date strings pattern to find date string format and use
datetime.strptime() - Use
dateutil.parser()
Is this correct? Alternative 1 (harder and may require maintenance in the future) has advantages, such as performance?
The
parse()method of dateutil is very flexible and will parse almost anything you throw at it.However, because of that flexibility, if your input is limited to a certain number of patterns, custom code that checks for those patterns then uses
datetime.datetime.strptime()could easily beat it.Since this depends entirely on the number of patterns you need to test for, the only thing you can do is measure which one will be faster for your specific usecases.