使用Python Pandas处理日期和时间

使用Python Pandas处理日期和时间

在处理数据的过程中,遇到时间序列数据是非常常见的。在处理时间序列数据时,Pandas是一个非常有用的工具。

Pandas提供了一套不同的工具,使用这些工具我们可以对日期时间数据执行所有必要的任务。让我们试着通过下面讨论的例子来理解。

代码#1:创建一个日期数据框架

import pandas as pd
 
# Create dates dataframe with frequency 
data = pd.date_range('1/1/2011', periods = 10, freq ='H')
 
data
Python

输出:

使用Python Pandas处理日期和时间

代码#2:创建日期范围并显示基本特征

# Create date and time with dataframe
data = pd.date_range('1/1/2011', periods = 10, freq ='H')
 
x = pd.datetime.now()
x.month, x.year
Python

输出:

(9, 2018)
Python

日期特征可分为两类。第一类是某一时期的时间时刻,第二类是某一时期以来的时间。这些特征对于理解数据中的模式非常有用。

将一个给定的日期划分为特征 –

pandas.Series.dt.year返回日期时间的年份。
pandas.Series.dt.month返回日期时间的月份。
pandas.Series.dt.day返回日期时间的日期。
pandas.Series.dt.hour返回日期时间的小时。
pandas.Series.dt.minute返回日期时间的分钟。
从这里可以参考所有的日期时间属性。

代码#3:将日期和时间分成独立的功能

# Create date and time with dataframe
rng = pd.DataFrame()
rng['date'] = pd.date_range('1/1/2011', periods = 72, freq ='H')
 
# Print the dates in dd-mm-yy format
rng[:5]
 
# Create features for year, month, day, hour, and minute
rng['year'] = rng['date'].dt.year
rng['month'] = rng['date'].dt.month
rng['day'] = rng['date'].dt.day
rng['hour'] = rng['date'].dt.hour
rng['minute'] = rng['date'].dt.minute
 
# Print the dates divided into features
rng.head(3)
Python

输出:

使用Python Pandas处理日期和时间

代码#4:要获得现在的时间,使用Timestamp.now(),然后将时间戳转换成数据时间,直接访问年、月或日。

# Input present datetime using Timestamp
t = pandas.tslib.Timestamp.now()
t
Python
Timestamp('2018-09-18 17:18:49.101496')
Python
# Convert timestamp to datetime
t.to_datetime()
Python
datetime.datetime(2018, 9, 18, 17, 18, 49, 101496)
Python
# Directly access and print the features
t.year
t.month
t.day
t.hour
t.minute
t.second
Python
2018
8
25
15
53
Python

让我们在一个真实的数据集uforeports上分析一下这个问题。

import pandas as pd
 
url = 'http://bit.ly/uforeports'
 
# read csv file
df = pd.read_csv(url)          
df.head()
Python

输出:

使用Python Pandas处理日期和时间

# Convert the Time column to datetime format
df['Time'] = pd.to_datetime(df.Time)
 
df.head()
Python

使用Python Pandas处理日期和时间

# shows the type of each column data
df.dtypes
Python
City                       object
Colors Reported            object
Shape Reported             object
State                      object
Time               datetime64[ns]
dtype: object
Python
# Get hour detail from time data
df.Time.dt.hour.head()
Python
0    22
1    20
2    14
3    13
4    19
Name: Time, dtype: int64
Python
# Get name of each date
df.Time.dt.weekday_name.head()
Python
0     Sunday
1     Monday
2     Sunday
3     Monday
4    Tuesday
Name: Time, dtype: object
Python
# Get ordinal day of the year
df.Time.dt.dayofyear.head()
Python
0    152
1    181
2     46
3    152
4    108
Name: Time, dtype: int64
Python

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Pandas 日期时间

登录

注册