跳至内容

日期时间

您可以将CLI 参数指定为 Python datetime

您的函数将接收一个标准的 Python datetime 对象,并且您的编辑器将再次为您提供代码补全等功能。

from datetime import datetime

import typer


def main(birth: datetime):
    print(f"Interesting day to be born: {birth}")
    print(f"Birth hour: {birth.hour}")


if __name__ == "__main__":
    typer.run(main)

Typer 将接受以下格式的任何字符串

  • %Y-%m-%d
  • %Y-%m-%dT%H:%M:%S
  • %Y-%m-%d %H:%M:%S

检查它

$ python main.py --help

Usage: main.py [OPTIONS] BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]

Arguments:
  BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S][required]

Options:
  --help                Show this message and exit.

// Pass a datetime
$ python main.py 1956-01-31T10:00:00

Interesting day to be born: 1956-01-31 10:00:00
Birth hour: 10

// An invalid date
$ python 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'.

自定义日期格式

您还可以使用 formats 参数自定义接收的 datetime 格式。

formats 接收一个字符串列表,其中包含将传递给 datetime.strptime() 的日期格式。

例如,假设您想接受 ISO 格式的日期时间,但出于某种奇怪的原因,您还想接受以下格式:

  • 首先是月份
  • 然后是日期
  • 然后是年份
  • 用 "/" 分隔

...这是一个疯狂的例子,但假设您也需要这种奇怪的格式

from datetime import datetime

import typer
from typing_extensions import Annotated


def main(
    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)

提示

如果可能,建议使用 Annotated 版本。

from datetime import datetime

import typer


def main(
    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)

提示

注意 formats 中的最后一个字符串:"%m/%d/%Y"

检查它

// ISO dates work
$ python main.py 1969-10-29

Launch will be at: 1969-10-29 00:00:00

// But the strange custom format also works
$ python main.py 10/29/1969

Launch will be at: 1969-10-29 00:00:00