Ame*_*ina 16 python timestamp numpy pandas
在以下系列中:
0 1411161507178
1 1411138436009
2 1411123732180
3 1411167606146
4 1411124780140
5 1411159331327
6 1411131745474
7 1411151831454
8 1411152487758
9 1411137160544
Name: my_series, dtype: int64
Run Code Online (Sandbox Code Playgroud)
此命令(转换为时间戳,本地化并转换为EST)有效:
pd.to_datetime(my_series, unit='ms').apply(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern'))
Run Code Online (Sandbox Code Playgroud)
但是这个失败了:
pd.to_datetime(my_series, unit='ms').tz_localize('UTC').tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)
有:
TypeError Traceback (most recent call last)
<ipython-input-3-58187a4b60f8> in <module>()
----> 1 lua = pd.to_datetime(df[column], unit='ms').tz_localize('UTC').tz_convert('US/Eastern')
/Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst)
3492 ax_name = self._get_axis_name(axis)
3493 raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' %
-> 3494 ax_name)
3495 else:
3496 ax = DatetimeIndex([],tz=tz)
TypeError: index is not a valid DatetimeIndex or PeriodIndex
Run Code Online (Sandbox Code Playgroud)
这一个是这样的:
my_series.tz_localize('UTC').tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)
有:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-0a7cb1e94e1e> in <module>()
----> 1 lua = df[column].tz_localize('UTC').tz_convert('US/Eastern')
/Users/josh/anaconda/envs/py34/lib/python3.4/site-packages/pandas/core/generic.py in tz_localize(self, tz, axis, copy, infer_dst)
3492 ax_name = self._get_axis_name(axis)
3493 raise TypeError('%s is not a valid DatetimeIndex or PeriodIndex' %
-> 3494 ax_name)
3495 else:
3496 ax = DatetimeIndex([],tz=tz)
TypeError: index is not a valid DatetimeIndex or PeriodIndex
Run Code Online (Sandbox Code Playgroud)
据我所知,上面的第二种方法(第一种方法失败)应该有效.为什么会失败?
Joh*_*nck 45
正如杰夫的回答所提到的那样,tz_localize()
并对tz_convert()
索引采取行动,而非数据.这对我来说也是一个巨大的惊喜.
自Jeff撰写回答以来,Pandas 0.15添加了一个新的Series.dt
访问器来帮助您的用例.你现在可以这样做:
pd.to_datetime(my_series, unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)
tz_localize/tz_convert
作用于对象的INDEX,而不是作用于值.最简单的方法是将其转换为索引然后进行本地化和转换.如果你想要一个系列回来,你可以使用to_series()
In [47]: pd.DatetimeIndex(pd.to_datetime(s,unit='ms')).tz_localize('UTC').tz_convert('US/Eastern')
Out[47]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-09-19 17:18:27.178000-04:00, ..., 2014-09-19 10:32:40.544000-04:00]
Length: 10, Freq: None, Timezone: US/Eastern
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8684 次 |
最近记录: |