在熊猫中,如何将自 1970 年 1 月 1 日以来的毫秒转换为数据类型时间戳?



在python3和pandas中,我有一个数据帧,其中日期为整数,表示自1970年1月1日00:00:00 UTC以来的毫秒数

presidentes["Data distribuição"].head()
0    1367193600000.0
1    1252886400000.0
2    1063929600000.0
3    1196294400000.0
4    1254873600000.0
Name: Data distribuição, dtype: object

我想转换为数据类型时间戳并尝试过这样

presidentes['Data distribuição'] = pd.to_datetime(presidentes['Data distribuição'], unit='s')
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
pandas/_libs/tslib.pyx in pandas._libs.tslib.array_with_unit_to_datetime()
pandas/_libs/tslibs/timedeltas.pyx in pandas._libs.tslibs.timedeltas.cast_from_unit()
OverflowError: Python int too large to convert to C long
During handling of the above exception, another exception occurred:
OutOfBoundsDatetime                       Traceback (most recent call last)
<ipython-input-10-53c23a37f5b2> in <module>
----> 1 presidentes['Data distribuição'] = pd.to_datetime(presidentes['Data distribuição'], unit='s')
~/Documentos/Code/publique_se/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin, cache)
590         else:
591             from pandas import Series
--> 592             values = convert_listlike(arg._values, True, format)
593             result = Series(values, index=arg.index, name=arg.name)
594     elif isinstance(arg, (ABCDataFrame, compat.MutableMapping)):
~/Documentos/Code/publique_se/lib/python3.6/site-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, box, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
201         arg = getattr(arg, 'values', arg)
202         result = tslib.array_with_unit_to_datetime(arg, unit,
--> 203                                                    errors=errors)
204         if box:
205             if errors == 'ignore':
pandas/_libs/tslib.pyx in pandas._libs.tslib.array_with_unit_to_datetime()
OutOfBoundsDatetime: cannot convert input 1367193600000.0 with the unit 's'

请问还有其他方法可以执行此转换吗?

更改为unit='ms'似乎有效:

presidentes['Data distribuição'] = pd.to_datetime(presidentes['Data distribuição'], unit='ms')
presidentes['Data distribuição'].head()
0   2013-04-29
1   2009-09-14
2   2003-09-19
3   2007-11-29
4   2009-10-07

最新更新