You can specify a CLI parameter as a Python datetime.
Your function will receive a standard Python datetime object, and again, your editor will give you completion, etc.
fromdatetimeimportdatetimeimporttyperdefmain(birth:datetime):print(f"Interesting day to be born: {birth}")print(f"Birth hour: {birth.hour}")if__name__=="__main__":typer.run(main)
Typer will accept any string from the following formats:
%Y-%m-%d
%Y-%m-%dT%H:%M:%S
%Y-%m-%d %H:%M:%S
Check it:
fast βpython main.py --help Usage: main.py [OPTIONS] BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]
π¬ Pass a datetimepython main.py 1956-01-31T10:00:00 Interesting day to be born: 1956-01-31 10:00:00 Birth hour: 10
π¬ An invalid datepython main.py july-19-1989 Usage: main.py [OPTIONS] [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d%H:%M:%S]
Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': 'july-19-1989' does not match the formats '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'.
You can also customize the formats received for the datetime with the formats parameter.
formats receives a list of strings with the date formats that would be passed to datetime.strptime().
For example, let's imagine that you want to accept an ISO formatted datetime, but for some strange reason, you also want to accept a format with:
first the month
then the day
then the year
separated with "/"
...It's a crazy example, but let's say you also needed that strange format:
fromdatetimeimportdatetimeimporttyperfromtyping_extensionsimportAnnotateddefmain(launch_date:Annotated[datetime,typer.Argument(formats=["%Y-%m-%d","%Y-%m-%dT%H:%M:%S","%Y-%m-%d %H:%M:%S","%m/%d/%Y"]),],):print(f"Launch will be at: {launch_date}")if__name__=="__main__":typer.run(main)
Tip
Prefer to use the Annotated version if possible.
fromdatetimeimportdatetimeimporttyperdefmain(launch_date:datetime=typer.Argument(...,formats=["%Y-%m-%d","%Y-%m-%dT%H:%M:%S","%Y-%m-%d %H:%M:%S","%m/%d/%Y"]),):print(f"Launch will be at: {launch_date}")if__name__=="__main__":typer.run(main)
Tip
Notice the last string in formats: "%m/%d/%Y".
Check it:
fast βπ¬ ISO dates workpython main.py 1969-10-29 Launch will be at: 1969-10-29 00:00:00
π¬ But the strange custom format also workspython main.py 10/29/1969 Launch will be at: 1969-10-29 00:00:00