【问题标题】:Return Value from time.strptime()time.strptime() 的返回值
【发布时间】:2014-12-20 03:16:12
【问题描述】:

我在我的 Python 程序中使用t = time.strptime() 并想检查它是否无法返回有效结构。

当我在 C 中编程时,我曾经检查返回值 NULL 以指示进行了无效调用。但是,这似乎不适用于 Python。我还检查了not t-1。我在这个阶段要做的是检查用户是否输入了无效的日期时间,而不单独检查每个字段是否存在错误,例如 2014 年 2 月 31 日等。

如何查看返回值?

【问题讨论】:

    标签: python python-2.7 time strptime


    【解决方案1】:

    Python 使用exceptions 传达错误的输入。如果time.strptime() 没有引发异常,则返回值是正确的,您不必自己验证。

    如果引发异常,您可以使用try...except 语句捕获它:

    try:
        t = time.strptime(userinput, format)
    except ValueError:
        # exception raised, not valid input, give feedback to user
    

    演示:

    >>> import time
    >>> time.strptime('01/02/2014 10:42:36', '%d/%m/%Y %H:%M:%S')
    time.struct_time(tm_year=2014, tm_mon=2, tm_mday=1, tm_hour=10, tm_min=42, tm_sec=36, tm_wday=5, tm_yday=32, tm_isdst=-1)
    >>> time.strptime('31/02/2014 10:42:36', '%d/%m/%Y %H:%M:%S')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 494, in _strptime_time
        tt = _strptime(data_string, format)[0]
      File "/Users/mpietre/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 465, in _strptime
        datetime_date(year, 1, 1).toordinal() + 1
    ValueError: day is out of range for month
    

    请注意,此处抛出异常是因为 31 超出了 2 月的有效天数范围。

    【讨论】:

    • 查看了两本 Python 书籍,但没有记录。问题现已解决!
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2010-11-18
    • 2012-03-02
    • 2012-08-30
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多