Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer date from SPSS to Python date

I have dates imported from SPSS to Python via pandas. The dates are imported as integers (ordinal). For instance the date "2015-08-02" is imported as 13657852800. When I try

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'

I also tried the following after I learn spss origin date is "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

How to convert spss ordinal integer date into an actual date in python using panda's to_datetime function?

like image 835
Chriss Paul Avatar asked Nov 24 '25 13:11

Chriss Paul


1 Answers

After some time, I came up with a solution to this. To make the origins of SPSS and Python match each other is necessary to rescale the integer from SPSS with the number 12219379200 i.e. the number of seconds existing between "1582-10-14" and "1970-01-01" (the origin used by to_datetime)

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

Returns

Timestamp('2015-08-02 00:00:00')
like image 89
Chriss Paul Avatar answered Nov 26 '25 04:11

Chriss Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!