Is there a Python equivalent to C#'s DateTime.TryParse()?

Is there an equivalent to C#'s DateTime.TryParse() in Python?

Edit:

I'm referring to the fact that it avoids throwing an exception, not the fact that it guesses the format.


If you don't want the exception, catch the exception.

try:
    d = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
except ValueError:
    d = None

In the zen of python, explicit is better than implicit. strptime always returns a datetime parsed in the exact format specified. This makes sense, because you have to define the behavior in case of failure, maybe what you really want is.

except ValueError:
    d = datetime.datetime.now()

or

except ValueError:
    d = datetime.datetime.fromtimestamp(0)

or

except ValueError:
    raise WebFramework.ServerError(404, "Invalid date")

By making it explicit, it's clear to the next person who reads it what the failover behavior is, and that it is what you need it to be.


or maybe you're confident that the date cannot be invalid, it's coming from a database DATETIME, column, in which case there wont' be an exception to catch, and so don't catch it.


No, what you're asking for is not idiomatic Python, and so there generally won't be functions that discard errors like that in the standard library. The relevant standard library modules are documented here:

http://docs.python.org/library/datetime.html

http://docs.python.org/library/time.html

The parsing functions all raise exceptions on invalid input.

However, as the other answers have stated, it wouldn't be terribly difficult to construct one for your application (your question was phrased "in Python" rather than "in the Python standard library" so it's not clear if assistance writing such a function "in Python" is answering the question or not).


这是一个等效的功能实现

import datetime

def try_strptime(s, format):
    """
    @param s the string to parse
    @param format the format to attempt parsing of the given string
    @return the parsed datetime or None on failure to parse 
    @see datetime.datetime.strptime
    """
    try:
        date = datetime.datetime.strptime(s, format)
    except ValueError:
        date = None
    return date
链接地址: http://www.djcxy.com/p/25184.html

上一篇: 将字符串转换为DateTime

下一篇: 有没有一个相当于C#的DateTime.TryParse()的Python?