在pandas中,如何将从1970年1月1日起的毫秒数转换为时间戳数据类型?

2024-05-20 00:38:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

我想转换为数据类型timestamp并尝试如下

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'

请问是否有其他方法来执行此转换?你知道吗


Tags: toinformatconvertpandasdatadatetimewith
1条回答
网友
1楼 · 发布于 2024-05-20 00:38:21

改成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

相关问题 更多 >