Python | Панды DatetimeIndex.strftime ()

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Pandas DatetimeIndex.strftime() function convert to Index using specified date_format. The function return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library.

Syntax: DatetimeIndex.strftime(date_format)

Parameters :
date_format : Date format string (e.g. “%Y-%m-%d”).

Return : Index of formatted strings

Example #1: Use DatetimeIndex.strftime() function to convert the given DatetimeIndex object to the specified format.

# 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)

Выход :

Now we want to convert the given DatetimeIndex object to ("%B %d, %Y, %r") format.

# change the datetime format.
didx.strftime("% B % d, % Y, % r")

Output :

As we can see in the output, the function has changed the format of the DatetimeIndex object to the desired format.
 
Example #2: Use DatetimeIndex.strftime() function to convert the given DatetimeIndex object to the specified format.

# 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)

Выход :

Now we want to convert the given DatetimeIndex object to ("%B %Y, %r") format.

# change the datetime format.
didx.strftime("% B % Y, % r")

Выход :

Как видно из вывода, функция изменила формат объекта DatetimeIndex на желаемый формат.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.