Python convert random string date format to Datetime

Development in PHP is easy or it may be just that I’ve been writing code in PHP for long time. And anytime I had a string date that needs to be converted in another format, all that was required was.

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

It’s that simple. Do not need any package or library, this is built-in functionality. Now the original date, could be Y-m-d or Y-m-d H:i or Y-m-d H:i:s, where H is hour, i is minute and s is seconds, the above example works for all formats.

This week I had a small python script to fix. Firstly, for almost anything in Python you need to import packages and I used datetime package, the issue with this was datetime.strptime(date, format) expects date to be formatted same as format for it to convert into datetime object.

For example, if the date was say 2021-06-10 11:10 and the format provided was %Y-%m-%d %H:%M:%S it just wouldn’t work. Python expects the format be %Y-%m-%d %H:%M that is without expecting seconds.

Fix: After a few google searches and trials came across this.

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

The only library I was able to find was dateutil.parser which would convert any string date to datetime object be it 2010-03-21 or 2010-03-21 10:12 or 2010-03-21 10:12:13.