首页 > 解决方案 > 从 SPSS 到 Python 日期的整数日期

问题描述

我通过熊猫将日期从 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

python -如何使用panda的to_datetime函数将spss序数整数日期转换为python中的实际日期?

标签: pythonpandasdatespss

解决方案


一段时间后,我想出了一个解决方案。为了使 SPSS 和 Python 的起源相互匹配,有必要用数字重新调整 SPSS 中的整数,即存在于和12219379200之间的秒数(由 使用的起源)"1582-10-14""1970-01-01"to_datetime

pd.to_datetime(13657852800-12219379200, unit="s")

退货

Timestamp('2015-08-02 00:00:00')

推荐阅读