![](/img/trans.png)
[英]python: convert year/month/day/hour/min/second to # seconds since Jan 1 1970
[英]In pandas, how to convert milliseconds since Jan 1, 1970 to datatype timestamp?
在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.