我有通过 pandas 从 SPSS 导入 Python 的日期。日期作为整数(序数)导入。例如,日期 "2015-08-02" 被导入为 13657852800。当我尝试
pd.to_datetime(13657852800, unit="s")
Traceback (most recent call last):
File "<ipython-input-39-ae44044ad39e>", line 1, in <module>
pd.to_datetime(13657852800, unit="s")
File "/anaconda3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 611, in to_datetime
result = convert_listlike(np.array([arg]), box, format)[0]
File "/anaconda3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 203, in _convert_listlike_datetimes
errors=errors)
File "pandas/_libs/tslib.pyx", line 356, in pandas._libs.tslib.array_with_unit_to_datetime
OutOfBoundsDatetime: cannot convert input with unit 's'
在得知 spss 原始日期为 "1582-10-14"
pd.to_datetime(13657852800, unit="us", origin="1582-10-14")
Traceback (most recent call last):
File "<ipython-input-38-a90cfe340ca5>", line 1, in <module>
pd.to_datetime(13657852800, unit="us", origin="1582-10-14")
File "/anaconda3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 571, in to_datetime
arg = _adjust_to_origin(arg, origin, unit)
File "/anaconda3/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 379, in _adjust_to_origin
"origin {origin} is Out of Bounds".format(origin=origin))
OutOfBoundsDatetime: origin 1582-10-14 is Out of Bounds
如何使用 panda 的 to_datetime 函数将 spss 序数整数日期转换为 python 中的实际日期?
请您参考如下方法:
一段时间后,我想出了一个解决方案。为了使 SPSS 和 Python 的起源相互匹配,有必要用数字 12219379200 重新缩放 SPSS 中的整数,即 “1582-10-14” 之间存在的秒数> 和 "1970-01-01"(to_datetime 使用的原点)
pd.to_datetime(13657852800-12219379200, unit="s")
返回
Timestamp('2015-08-02 00:00:00')
