from dateutil.parser import parser
from datetime import datetime


def datetime_string(string, custom_format=None):
	"""
	Takes a string and parses it into a datetime object with the dateutil module if present.
	If not it will fall back to a more rudimentary method of using strptime with a list of
	predefined formats with the option of passing in a custom format to try before the others.
	The first one to parse correctly gets returned.
	"""
	try:
		# noinspection PyUnresolvedReferences
		return parser().parse(string)
	except ImportError:
		string = string.replace('/', '-')
		formats = [
			'%Y',
			'%Y-%m',
			'%Y-%m-%d',
			'%Y-%m-%d %H',
			'%Y-%m-%d %I %p'
			'%Y-%m-%d %H:%M',
			'%Y-%m-%d %I:%M %p'
			'%Y-%m-%d %H:%M:%S',
			'%Y-%m-%d %I:%M:%S %p'
		]
		if custom_format:
			formats.insert(0, custom_format)
		for f in formats:
			try:
				return datetime.strptime(string, f)
			except ValueError:
				continue
		raise ValueError('The string did not match any configured format')