Pandas DateTime

在 Pandas 中,DateTime 是一种表示时间点的数据类型。当处理股票价格、天气记录、经济指标等时间序列数据时,它特别有用。

我们使用 to_datetime() 函数将字符串转换为 DateTime 对象。让我们看一个例子。

import pandas as pd

# create a datetime string
date_string = '2001-12-24 12:38'

print("String:", date_string)

# convert string to datetime date = pd.to_datetime(date_string)
print("DateTime:", date) print(type(date))

输出

String: 2001-12-24 12:38
DateTime: 2001-12-24 12:38:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'>

在上面的示例中,我们使用 to_datetime()string 转换为 DateTime


将字符串转换为 DateTime

如上例所示,我们可以使用 to_datetime() 将任何有效字符串转换为 DateTime。

让我们看一些示例。

示例:带默认参数的 to_datetime()

import pandas as pd

# create a dataframe with date strings
df = pd.DataFrame({'date': ['2021-01-13', '2022-10-22', '2023-12-03']})

# convert the 'date' column to datetime df['date'] = pd.to_datetime(df['date'])
print(df)

输出

        date
0 2021-01-13
1 2022-10-22
2 2023-12-03

在此示例中,我们将 'date' 列从字符串数据类型转换为 DateTime 数据类型。

默认情况下,Pandas 的 to_datetime() 函数期望日期字符串的格式为 YYYY-MM-DD


示例:带日优先格式的 to_datetime()

import pandas as pd

# create a dataframe with date strings in day-first format
df = pd.DataFrame({'date': ['13-02-2021', '22-03-2022', '30-04-2023']})

# convert the 'date' column to datetime with day-first format
df['date'] = pd.to_datetime(df['date'], dayfirst=True)

print(df)

输出

        date
0 2021-02-13
1 2022-03-22
2 2023-04-30

在此示例中,日期列包含格式为 DD-MM-YYYY 的字符串。

我们将 dayfirst=True 传递给 to_datetime() 函数,以将日优先格式的字符串转换为 DateTime。

请注意,DateTime 数据始终采用 YYYY-MM-DD 格式。


示例:带自定义格式的 to_datetime()

import pandas as pd

# create a dataframe with date strings in custom format
df = pd.DataFrame({'date': ['2021/22/01', '2022/13/01', '2023/30/03']})

# convert the 'date' column to datetime with custom format
df['date'] = pd.to_datetime(df['date'], format='%Y/%d/%m')

print(df)

输出

        date
0 2021-01-22
1 2022-01-13
2 2023-03-30

在此示例中,我们将日期列(格式为 YY/DD/MM)从字符串转换为 DateTime 数据类型。


从多个列获取 DateTime

我们还可以使用 to_datetime() 函数从多个列组合 DateTime。

让我们看一个例子。

import pandas as pd

# create a dataframe with separate date and time columns
df = pd.DataFrame({'year': [2021, 2022, 2023],
                   'month': [1, 2, 3],
                   'day': [1, 2, 3],
                   'hour': [10, 11, 12],
                   'minute': [30, 45, 0],
                   'second': [0, 0, 0]})

# combine date and time columns to create a datetime column df['datetime'] = pd.to_datetime(df[['year', 'month', 'day', 'hour', 'minute', 'second']])
print(df)

输出

   year  month  day  hour  minute  second            datetime
0  2021      1    1    10      30       0 2021-01-01 10:30:00
1  2022      2    2    11      45       0 2022-02-02 11:45:00
2  2023      3    3    12       0       0 2023-03-03 12:00:00

在此示例中,我们通过将列列表传递给 to_datetime() 函数,从不同列组合了完整的日期和时间。


从 DateTime 获取年、月和日

我们可以分别使用内置属性 dt.yeardt.monthdt.day 从 Pandas DateTime 对象获取年、月和日。

让我们看一个例子。

import pandas as pd

# create a dataframe with a datetime column
df = pd.DataFrame({'datetime': ['2021-01-01', '2022-02-02', '2023-03-03']})

# convert the 'datetime' column to datetime type
df['datetime'] = pd.to_datetime(df['datetime'])

# extract year, month, and day into separate columns df['year'] = df['datetime'].dt.year df['month'] = df['datetime'].dt.month df['day'] = df['datetime'].dt.day
print(df)

输出

  datetime    year  month  day
0 2021-01-01  2021      1    1
1 2022-02-02  2022      2    2
2 2023-03-03  2023      3    3

获取星期几、一年中的第几周和闰年

我们还有内置属性可以获取星期几、一年中的第几周以及检查给定年份是否为闰年。

例如,

import pandas as pd

# create a dataframe with a datetime column
df = pd.DataFrame({'datetime': ['2021-01-01', '2024-02-02', '2023-03-03']})

# convert the 'datetime' column to datetime type
df['datetime'] = pd.to_datetime(df['datetime'])

# get the day of the week df['day_of_week'] = df['datetime'].dt.day_name()
# get the week of the year df['week_of_year'] = df['datetime'].dt.isocalendar().week
# check for leap year df['leap_year'] = df['datetime'].dt.is_leap_year
print(df)

输出

  datetime  day_of_week  week_of_year  leap_year
0 2021-01-01      Friday           53       False
1 2024-02-02      Friday            5        True
2 2023-03-03      Friday            9        False

这里,

  • dt.day_name() - 返回星期几
  • dt.isocalender().week - week 返回一年中的第几周,并且
  • dt.is_leap_year - 检查 DateTime 是否为闰年。

Pandas 中的 DateTime 索引

Pandas 中的 DateTime 索引使用 DateTime 值作为索引值。

当处理天气数据、股票价格和其他时间相关数据等时间序列数据时,datetime 索引特别有用,因为它允许基于时间戳进行自然的组织和操作。

让我们看一个例子。

import pandas as pd

# create a list of datetime values
dates = ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05']

# create a DataFrame with a DateTimeIndex df = pd.DataFrame({'values': [10, 20, 30, 40, 50]}, index=pd.to_datetime(dates))
print(df)

输出

            values
2021-01-01      10
2021-01-02      20
2021-01-03      30
2021-01-04      40
2021-01-05      50

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战