from pathlib import Path
from datetime import datetime


def date_from_cbin_filename(cbin_filename):
    """extracts date as a string from a .cbin filename
    and converts to a datetime object

    Parameters
    ----------
    cbin_filename : str
        path to a .cbin file

    Returns
    -------
    dt : datetime
        convert from string using strptime function

    Examples
    --------
    >>> cbin_filename = 'gy6or6_baseline_220312_0836.3.cbin'
    >>> dt = date_from_cbin_filename(cbin_filename)
    """
    name = Path(cbin_filename).name
    splitname = name.split('.')  # splits into: stem, file number, extension
    splitname = splitname[0]  # just keep the stem
    splitname = splitname.split('_')  # further split stem; last two will be date + time
    date, time = splitname[-2:]
    dt = date + '-' + time
    dt = datetime.strptime(dt, '%d%m%y-%H%M')
    return dt