Skip to content

strftime formatting #150

@bendichter

Description

@bendichter

Thanks for all the hard work on this package!

I'd like to make a request, similar to #62 but maybe a bit simpler. I'd like to be able to specify how I would like a datetime to be parsed. For example:

from parse import parse
parse("my date:{my_date:%Y%M%d}", "my date:20200403").groups = {"my_date": datetime.datetime(2020, 4, 3)}

You'd need to construct a regex expression from a date format:

dt_format_to_regex = {symbol: "[0-9]{2}" for symbol in "ymdIMSUW"}
dt_format_to_regex.update({"-" + symbol: "[0-9]{1,2}" for symbol in "ymdIMS"})

dt_format_to_regex.update(
    {
        "a": "[Sun|Mon|Tue|Wed|Thu|Fri|Sat]",
        "A": "[Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday]",
        "Y": "[0-9]{4}",
        "H": "[0-9]{1,2}",
        "B": "[January|February|March|April|May|June|July|August|September|October|November|December]",
        "b": "[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]",
        "f": "[0-9]{6}",
        "p": "[AM|PM]",
        "z": "[+|-][0-9]{4}",
        "j": "[0-9]{3}",
        "-j": "[0-9]{1,3}",
    }
)


def get_regex_for_datetime_format(format_):
    regex = copy(format_)
    for k, v in dt_format_to_regex.items():
        regex = regex.replace(f"%{k}", v)
    return regex

and you'd need to parse the string into a datetime, which is actually quite easy because you can just rely on datetime.datetime.strptime:

self._type_conversions[group] = lambda x: datetime.strptime(x, format)

I guess the remaining bit would be to determine if the formatting is of a datetime, but that doesn't seem that hard to me. As a first pass, you could just look for "%Y" in the format string. Technically datetime.datetime.strptime does allow you to parse datestrings that do not have a year, but that results are non-sensical, so it would be fine to not support them:

print(datetime.datetime.strptime("Sun", "%a"))
print(datetime.datetime.strptime("Mon", "%a"))
datetime.datetime(1900, 1, 1, 0, 0)
datetime.datetime(1900, 1, 1, 0, 0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions