from datetime import datetime


def DatetimeFromString(date):
  """Parses a datetime from a serialized string."""
  if date == 'None':
    return None
  if not date or isinstance(date, datetime):
    return date

  # Strip bad characters.
  date = date.strip('\t\n ')
  valid_formats = [
      '%Y-%m-%d %H:%M:%S.%f %Z',
      '%Y-%m-%d %H:%M:%S.%f000',
      '%Y-%m-%d %H:%M:%S.%f',
      '%Y-%m-%d %H:%M:%S %Z',
      '%Y-%m-%d %H:%M:%S',
      '%Y-%m-%dT%H:%M:%S.%f',
      '%Y-%m-%dT%H:%M:%S',
      '%Y-%m-%d',
  ]
  for format_str in valid_formats:
    try:
      return datetime.strptime(date, format_str)
    except ValueError:
      pass
  raise ValueError('%s is not in a known datetime format' % date)