如何获取 pandas datetime64 列和 1582 年 10 月 14 日(公历)之间的时间增量(以秒为单位)?

How to get time delta in seconds between pandas datetime64 column and Oct 14 1582 (Gregorian calendar)?

我正在尝试将 pandas 数据帧转换为 SPSS 格式,但在转换 datetime64 变量时遇到问题。

使用以下代码:

import pandas as pd

import datetime as dt

df['date1'] =  (df['date'] - pd.Timestamp('1582-10-15 00:00')).astype('timedelta64[s]')

df['date1'] = (df['date'] - dt.datetime(1582, 10, 15)).astype('timedelta64[s]')

我收到 Out of bounds nanosecond timestamp: 1582-10-15 00:00:00 错误。

当我只是为了好玩而尝试使用 1982 时,它起作用了!

我知道很难找到从 1582 年到 1970 年的纪元和 UTC 时间等,但是有没有简单的方法? 非常感谢!

我相信 Timestamp 在这么久以前就中断了,因为没有记录如何处理各种闰秒以及一直没有处理的问题。所以你得到的错误是打破了最精确的时间。这就说得通了。说的是很久以前的日期不可能那么精确。

解决方案

改用dt.datetime。它不需要那么高的精度。

import pandas as pd

import datetime as dt

epoch = dt.datetime(1582, 10, 15)
date = dt.datetime(2016, 3, 31)

int((date - epoch).total_seconds())

Timestamp limitations

使用 docs:

中的提示进行一些破解
df = pd.DataFrame(pd.date_range('2016-01-01', periods=5, freq = 'D'), columns = ['date'])
df
Out[291]: 
        date
0 2016-01-01
1 2016-01-02
2 2016-01-03
3 2016-01-04
4 2016-01-05

# PeriodIndex:
pi = pd.PeriodIndex(df['date'].astype(str), freq='s')
pi
Out[293]: 
PeriodIndex(['2016-01-01 00:00:00', '2016-01-02 00:00:00',
             '2016-01-03 00:00:00', '2016-01-04 00:00:00',
             '2016-01-05 00:00:00'],
            dtype='int64', freq='S')

# Period:
p0 = pd.Period('1582-10-15 00:00', freq='s')
p0
Out[295]: Period('1582-10-15 00:00:00', 'S')

# Then this is an Int64Index (in seconds):
idx = pi - p0
idx
Out[296]: Int64Index([13670899200, 13670985600, 13671072000, 13671158400, 13671244800], dtype='int64')
# idx.values gives a numpy array