Python Pandas – 将时间转换为DateTimeIndex的午夜时间
要将时间转换为DateTimeIndex的午夜时间,请使用Pandas中的 DateTimeIndex.normalize() 。
首先,导入所需的库−
import pandas as pd
创建一个周期为7,频率为H即小时的DatetimeIndex−
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')
显示DatetimeIndex−
print("DateTimeIndex...\n", datetimeindex)
日期时间的时间组件将被转换为午夜即00:00:00−
print("\nNormalize (转换时间组件为午夜)...\n",
datetimeindex.normalize())
更多Pandas相关文章,请阅读:Pandas 教程
示例
以下是代码−
import pandas as pd
# 创建一个周期为7,频率为H即小时的DatetimeIndex
# 时区为Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')
# 显示DatetimeIndex
print("DateTimeIndex...\n", datetimeindex)
# 显示DatetimeIndex的频率
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)
# 日期时间的时间组件将被转换为午夜即00:00:00
print("\nNormalize (转换时间组件为午夜)...\n",
datetimeindex.normalize())
输出
将产生以下代码−
DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
'2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
'2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
'2021-11-01 14:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='10H')
DateTimeIndex frequency...
<10 * 小时>
Normalize (转换时间组件为午夜)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
'2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
'2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
'2021-11-01 00:00:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)
极客教程