Python 的状况

先来看看 date 类型吧!

In [1]: from datetime import dateIn [2]: date.minOut[2]: datetime.date(1, 1, 1)In [3]: str(date.min)Out[3]: '0001-01-01'In [4]: str(date.max)Out[4]: '9999-12-31'

能够看到 date 的取值范畴是 0001-01-019999-12-31

再来看看 datetime 吧!

In [5]: from datetime import datetimeIn [6]: str(datetime.min)Out[6]: '0001-01-01 00:00:00'In [7]: str(datetime.max)Out[7]: '9999-12-31 23:59:59.999999'

能够看到 datetime 的取值范畴是 0001-01-01 00:00:009999-12-31 23:59:59.999999

Mysql 的状况

来看看 mysql 的状况吧,上面的官网文档中的内容:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD hh:mm:ss' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

总结一下就是:

  • date 的取值范畴:1000-01-019999-12-31
  • timestamp 的取值范畴:1970-01-01 00:00:012038-01-19 03:14:07
  • datetime 的取值范畴:1000-01-01 00:00:009999-12-31 23:59:59

参考资料:mysql 文档

然而须要留神:

Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00'), if the SQL mode permits this conversion. The precise behavior depends on which if any of strict SQL mode and the NO_ZERO_DATE SQL mode are enabled; see Section 5.1.10, “Server SQL Modes”.

还有这部分:

翻译成人话的意思,就是 myql 会把有效的 date 设为 0000-00-00,有效的 datetime 和 timestamp 设为 0000-00-00 00:00:00

比方 2022-13-35 就是一个有效的 date,当把这个值插入到 mysql 中的时候,开启了严格模式的 mysql 会报错,未开启严格模式的 mysql 会转为 0000-00-00 保留。

所以咱们应用 Python 从 mysql 读取工夫类型的时候,肯定要留神这个坑!因为 0000-00-00 没有方法转成 Python 的 date 类型,会报错的!