我有一些时区信息存储在一个名为tz_pytz
-的变量中-我将其hdf5
与数据帧一起从文件中获取,但是现在这并不重要。
我有一个int64索引,表示从纪元以来的第二个值,我想将其视为带有时区信息的时间戳记:
>>> df = pd.DataFrame(h5file['time']).sec
Int64Index([0, ...], dtype='int64')
>>> dt = pd.to_datetime(df, unit='s')
>>> type(dt[0])
pandas.tslib.Timestamp
>>> dt[0].tz is None
True
>>> dt
0 2015-05-29 07:18:22
1 2015-05-29 07:18:23
...
4478 2015-05-29 08:33:06
4479 2015-05-29 08:33:07
Name: sec, Length: 4480, dtype: datetime64[ns]
这可以正常工作,但数据不支持时区(tz is None
)。如何根据我所在的时区使它知道时区py_pytz
?
使用.tz_localize
到时区添加到您的日期时间列:
In [12]:
df = pd.DataFrame(index=np.arange(10))
df['timestamp'] = pd.to_datetime(df.index, unit='s')
df['timestamp'] = df['timestamp'].dt.tz_localize('Asia/Hong_Kong')
df['timestamp']
Out[12]:
0 1970-01-01 00:00:00+08:00
1 1970-01-01 00:00:01+08:00
2 1970-01-01 00:00:02+08:00
3 1970-01-01 00:00:03+08:00
4 1970-01-01 00:00:04+08:00
5 1970-01-01 00:00:05+08:00
6 1970-01-01 00:00:06+08:00
7 1970-01-01 00:00:07+08:00
8 1970-01-01 00:00:08+08:00
9 1970-01-01 00:00:09+08:00
Name: timestamp, dtype: datetime64[ns, Asia/Hong_Kong]
这会将tz
信息添加/删除到您的时间戳列中,它接受字符串,pytz
或者dateutil.tz.tzfile
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句