Python Pandas DatetimeIndex.strftime()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。
Pandas DatetimeIndex.strftime()函数使用指定的date_format转换为索引。该函数返回一个由date_format指定的格式化字符串的索引,它支持与python标准库相同的字符串格式。
语法: DatetimeIndex.strftime(date_format)
参数 :
date_format :日期格式字符串(例如,”%Y-%m-%d”)。
返回:格式化字符串的索引
示例#1:使用DatetimeIndex.strftime()函数将给定的DatetimeIndex对象转换为指定格式。
# importing pandas as pd
import pandas as pd
# Create the DatetimeIndex
# Here 'Q' represents quarter end frequency
didx = pd.DatetimeIndex(start ='2000-01-15 08:00', freq ='Q',
periods = 4, tz ='Asia/Calcutta')
# Print the DatetimeIndex
print(didx)
输出 :
现在我们要将给定的DatetimeIndex对象转换为(’%B %d, %Y, %r’)格式。
# change the datetime format.
didx.strftime('% B % d, % Y, % r')
输出 :
正如我们在输出中看到的,该函数已经将DatetimeIndex对象的格式改为所需的格式。
示例#2:使用DatetimeIndex.strftime()函数将给定的DatetimeIndex对象转换为指定格式。
# importing pandas as pd
import pandas as pd
# Create the DatetimeIndex
# Here 'MS' represents month start frequency
didx = pd.date_range(pd.Timestamp("2000-01-15 08:00"),
periods = 5, freq ='MS')
# Print the DatetimeIndex
print(didx)
输出 :
现在我们要将给定的DatetimeIndex对象转换为(’%B %Y, %r’)格式。
# change the datetime format.
didx.strftime('% B % Y, % r')
输出 :
正如我们在输出中看到的,该函数已经将DatetimeIndex对象的格式改为所需的格式。