python 与 pandas 解析日期,如“0001-11-29 13:00:00 BC”

python with pandas to parse dates like "0001-11-29 13:00:00 BC"

我正在尝试使用 pandas 库读取一些 sql 数据,其中一列“customer_date”的值类似于“0001-11-29 13:00:00公元前”。我的查询因错误

而失败

ValueError: year 0 is out of range

请建议一种解析此类 date/timestamps 的方法。

这是我的代码。

import pandas as pd
from datetime import datetime, timedelta

session = ah.get_boto_session()
db = get_connection() **### Custom method**

pd.set_option('display.max_rows', None)
query = "SELECT customer_date FROM customer"
df = pd.read_sql(query, db, parse_dates=["customer_date"])
print(df.head())

db.dispose()

错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-d4e334c3f39c> in <module>()
 22 pd.set_option('display.max_rows', None)
 23 query = "SELECT customer_date FROM customer"
---> 24 df = pd.read_sql(query, db, parse_dates=["customer_date"])
 25 print(df.head())

ValueError: year 0 is out of range

您无法在 pandas 日期时间库中读取该日期 如果您尝试 pd.to_datetime("0001-11-29 13:00:00"),pandas 将引发越界异常

您应该使用大于 1676 的日期

也许您需要的是替换 sql 语句中的年份

这是有效的方法:

import pandas as pd
from datetime import datetime, timedelta

session = ah.get_boto_session()
db = get_connection() **### Custom method**

pd.set_option('display.max_rows', None)
query = "SELECT case when customer_date >= '1970-01-01' then customer_date else '1970-01-01' end AS customer_date FROM customer"
df = pd.read_sql(query, db)
print(df.head())

db.dispose()