Python Pandas - 将时间索引转换为不含有时区的 Series


若要将时间索引转换为不含有时区的 Series,请使用 datetimeindex.tz_convert(None).to_series()tz.convert(None) 用于排除时区。

首先,导入所需的库 -\n

import pandas as pd

使用周期 5 和频率为 S(即秒)创建一个时间索引 -\n

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

显示时间索引 -\n

print("DateTimeIndex...\n", datetimeindex)

将时间索引转换为 Series。使用“tz_convert()”并将其设置为“None”以排除时区 -\n

print("\nDateTimeIndex to series excluding the TimeZone...\n",
datetimeindex.tz_convert(None).to_series())

示例

如下的代码 −

import pandas as pd

# DatetimeIndex with period 5 and frequency as S i.e. seconds
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# Convert DateTimeIndex to Series
# Use the "tz_convert()" and set it to "None" to exclude the TimeZone
print("\nDateTimeIndex to series excluding the TimeZone...\n",
datetimeindex.tz_convert(None).to_series())

输出

生成以下代码 −

DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * Seconds>

DateTimeIndex to series excluding the TimeZone...
2021-10-17 20:50:32.261811624 2021-10-17 20:50:32.261811624
2021-10-17 20:51:12.261811624 2021-10-17 20:51:12.261811624
2021-10-17 20:51:52.261811624 2021-10-17 20:51:52.261811624
2021-10-17 20:52:32.261811624 2021-10-17 20:52:32.261811624
2021-10-17 20:53:12.261811624 2021-10-17 20:53:12.261811624
Freq: 40S, dtype: datetime64[ns]

更新日期: 19-10-2021

120 次浏览

开启你的 职业生涯

完成课程认证

立即开始
广告