python - 在 "time data does not match format"捕获无效的月/日

标签 python datetime

我正在使用以下代码(不是完整代码,只是相关位)转换日期字符串:

str_format = '%Y-%m-%d %H:%M:%S'
datetime.strptime('2015-13-23 13:43:23', str_format)

这会引发“时间数据与格式不匹配”​​,因为月份错误(13 不是有效月份)。

我想知道是否有可能让它在月份(或日期)无效时引发异常而不是因为日期无效而格式不匹配?下面清楚地表明 datetime 可以确定:

>>> print datetime(2015, 13, 23)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12

最佳答案

您始终可以解析文本,然后自己使用它来构建日期时间 - 或者如果适合您,可以预先验证它:

from datetime import datetime

def to_datetime(date_string):
    year = int(date_string[0:4])
    month = int(date_string[5:7])
    day = int(date_string[8:10])

    return datetime(year, month, day)

print(to_datetime('2015-13-23 13:42:13'))

抛出:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print(to_datetime('2015-13-23 13:42:13'))
  File "test.py", line 9, in to_datetime
    return datetime(year, month, day)
ValueError: month must be in 1..12

如果你想知道 datetime 是如何做到的 - 使用源代码,Luke!

>>> import datetime
>>> datetime.__file__
'/usr/lib/python3.5/datetime.py'

打开那个文件,你会发现:

def _check_date_fields(year, month, day):
    year = _check_int_field(year)
    month = _check_int_field(month)
    day = _check_int_field(day)
    if not MINYEAR <= year <= MAXYEAR:
        raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
    if not 1 <= month <= 12:
        raise ValueError('month must be in 1..12', month)
    dim = _days_in_month(year, month)
    if not 1 <= day <= dim:
        raise ValueError('day must be in 1..%d' % dim, day)
    return year, month, day

关于python - 在 "time data does not match format"捕获无效的月/日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34682129/

相关文章:

python - matplotlib.scatter 颜色参数不接受 numpy 数组

python - Pandas 中的日期格式

c# - 更改 ASCX 文件中的日期格式

r - date_breaks {scales} 改变 ggplot 中的日期刻度

sql - 按周对 SQL 结果进行分组并指定 "week-ending"天

php DateTime 转换unix时间戳

python - 这个将 'string' 视为 'list' 的回文代码如何工作?

python - pandas - 聚合数据框的内容

python - 选择节点和边形成具有属性的 networkx 图

python - 我在我的电脑上安装了python3.3.2,ubuntu12.04。还有埃里克 IDE