from datetime import datetime


def datetime_from_string(s):
    """
    parse datetime from a string

    returns a datetime object if the format could be parsed.
    raises ValueError if not.
    """
    s = s.strip()
    for ts_format in [
            # ISO-8601-like:
            '%Y-%m-%dT%H:%M:%S',
            '%Y-%m-%dT%H:%M',
            '%Y-%m-%d %H:%M:%S',
            '%Y-%m-%d %H:%M',
            # date tool output [C / en_US locale]:
            '%a %b %d %H:%M:%S %Z %Y',
            # for more, see https://xkcd.com/1179/
            ]:
        try:
            return datetime.strptime(s, ts_format)
        except ValueError:
            # didn't work with this format, try next
            pass
    else:
        raise ValueError('could not parse %r' % s)