如何从 pandas 数据框中的时间戳列中删除时区 [英] How to remove timezone from a Timestamp column in a pandas dataframe

查看:125
本文介绍了如何从 pandas 数据框中的时间戳列中删除时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了熊猫更改外汇DataFrame的时区,但我想使我的数据框时区的时间列幼稚,以实现与sqlite3数据库的互操作性.

I read Pandas change timezone for forex DataFrame but I'd like to make the time column of my dataframe timezone naive for interoperability with an sqlite3 database.

我的pandas数据框中的数据已经转换为UTC数据,但是我不想在数据库中维护该UTC时区信息.

The data in my pandas dataframe is already converted to UTC data, but I do not want to have to maintain this UTC timezone information in the database.

给出从其他来源获得的数据样本,看起来像这样:

Given a sample of the data derived from other sources, it looks like this:

print(type(testdata))
print(testdata)
print(testdata.applymap(type))

给予:

<class 'pandas.core.frame.DataFrame'>
                        time  navd88_ft  station_id  new
0  2018-03-07 01:31:02+00:00  -0.030332          13    5
1  2018-03-07 01:21:02+00:00  -0.121653          13    5
2  2018-03-07 01:26:02+00:00  -0.072945          13    5
3  2018-03-07 01:16:02+00:00  -0.139917          13    5
4  2018-03-07 01:11:02+00:00  -0.152085          13    5
                                     time        navd88_ft     station_id  \
0  <class 'pandas._libs.tslib.Timestamp'>  <class 'float'>  <class 'int'>   
1  <class 'pandas._libs.tslib.Timestamp'>  <class 'float'>  <class 'int'>   
2  <class 'pandas._libs.tslib.Timestamp'>  <class 'float'>  <class 'int'>   
3  <class 'pandas._libs.tslib.Timestamp'>  <class 'float'>  <class 'int'>   
4  <class 'pandas._libs.tslib.Timestamp'>  <class 'float'>  <class 'int'>   

             new  
0  <class 'int'>  
1  <class 'int'>  
2  <class 'int'>  
3  <class 'int'>  
4  <class 'int'>  

但是

newstamp = testdata['time'].tz_convert(None)

给出最终错误:

TypeError: index is not a valid DatetimeIndex or PeriodIndex

如何用时区天真的时间戳替换列?

What do I do to replace the column with a timezone naive timestamp?

推荐答案

您可以使用tz_localize更改时区,朴素的时间戳对应于时区None:

You can use tz_localize to change the time zone, a naive timestamp corresponds to time zone None:

testdata['time'].dt.tz_localize(None)

除非该列是索引,否则您必须调用方法dt才能访问pandas datetime函数.

Unless the column is an index you have to call method dt to access pandas datetime functions.

这篇关于如何从 pandas 数据框中的时间戳列中删除时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆