Pandas時(shí)間數(shù)據(jù)處理詳細(xì)教程
轉(zhuǎn)化時(shí)間類型
to_datetime()方法
to_datetime()方法支持將
int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like類型的數(shù)據(jù)轉(zhuǎn)化為時(shí)間類型
import pandas as pd
# str ---> 轉(zhuǎn)化為時(shí)間類型:
ret = pd.to_datetime('2022-3-9')
print(ret)
print(type(ret))
"""
2022-03-09 00:00:00
<class 'pandas._libs.tslibs.timestamps.Timestamp'> ---pandas中默認(rèn)支持的時(shí)間點(diǎn)的類型
"""
# 字符串的序列 --->轉(zhuǎn)化成時(shí)間類型:
ret = pd.to_datetime(['2022-3-9', '2022-3-8', '2022-3-7', '2022-3-6'])
print(ret)
print(type(ret))
"""
DatetimeIndex(['2022-03-09', '2022-03-08', '2022-03-07', '2022-03-06'], dtype='datetime64[ns]', freq=None)
<class 'pandas.core.indexes.datetimes.DatetimeIndex'> ----pandas中默認(rèn)支持的時(shí)間序列的類型
"""
# dtype = 'datetime64[ns]' ----> numpy中的時(shí)間數(shù)據(jù)類型!
DatetimeIndex()方法
DatetimeIndex()方法支持將一維 類數(shù)組( array-like (1-dimensional) )轉(zhuǎn)化為時(shí)間序列
# pd.DatetimeIndex 將 字符串序列 轉(zhuǎn)化為 時(shí)間序列 ret = pd.DatetimeIndex(['2022-3-9', '2022-3-8', '2022-3-7', '2022-3-6']) print(ret) print(type(ret)) """ DatetimeIndex(['2022-03-09', '2022-03-08', '2022-03-07', '2022-03-06'], dtype='datetime64[ns]', freq=None) <class 'pandas.core.indexes.datetimes.DatetimeIndex'> """
生成時(shí)間序列
使用date_range()方法可以生成時(shí)間序列。
時(shí)間序列一般不會主動生成,往往是在發(fā)生某個事情的時(shí)候,同時(shí)記錄一下發(fā)生的時(shí)間!
ret = pd.date_range(
start='2021-10-1', # 開始點(diǎn)
# end='2022-1-1', # 結(jié)束點(diǎn)
periods=5, # 生成的元素的個數(shù) 和結(jié)束點(diǎn)只需要出現(xiàn)一個即可!
freq='W', # 生成數(shù)據(jù)的步長或者頻率, W表示W(wǎng)eek(星期)
)
print(ret)
"""
DatetimeIndex(['2021-10-03', '2021-10-10', '2021-10-17', '2021-10-24', '2021-10-31'],
dtype='datetime64[ns]', freq='W-SUN')
"""
提取時(shí)間屬性
使用如下數(shù)據(jù)作為初始數(shù)據(jù)(type:<class ‘pandas.core.frame.DataFrame’>):

# 轉(zhuǎn)化為 pandas支持的時(shí)間序列之后再提取時(shí)間屬性! data.loc[:, 'time_list'] = pd.to_datetime(data.loc[:, 'time_list']) # 可以通過列表推導(dǎo)式來獲取時(shí)間屬性 # 年月日 data['year'] = [tmp.year for tmp in data.loc[:, 'time_list']] data['month'] = [tmp.month for tmp in data.loc[:, 'time_list']] data['day'] = [tmp.day for tmp in data.loc[:, 'time_list']] # 時(shí)分秒 data['hour'] = [tmp.hour for tmp in data.loc[:, 'time_list']] data['minute'] = [tmp.minute for tmp in data.loc[:, 'time_list']] data['second'] = [tmp.second for tmp in data.loc[:, 'time_list']] # 日期 data['date'] = [tmp.date() for tmp in data.loc[:, 'time_list']] # 時(shí)間 data['time'] = [tmp.time() for tmp in data.loc[:, 'time_list']] print(data)

# 一年中的第多少周
data['week'] = [tmp.week for tmp in data.loc[:, 'time_list']]
# 一周中的第多少天
data['weekday'] = [tmp.weekday() for tmp in data.loc[:, 'time_list']]
# 季度
data['quarter'] = [tmp.quarter for tmp in data.loc[:, 'time_list']]
# 一年中的第多少周 ---和week是一樣的
data['weekofyear'] = [tmp.weekofyear for tmp in data.loc[:, 'time_list']]
# 一周中的第多少天 ---和weekday是一樣的
data['dayofweek'] = [tmp.dayofweek for tmp in data.loc[:, 'time_list']]
# 一年中第 多少天
data['dayofyear'] = [tmp.dayofyear for tmp in data.loc[:, 'time_list']]
# 周幾 ---返回英文全拼
data['day_name'] = [tmp.day_name() for tmp in data.loc[:, 'time_list']]
# 是否為 閏年 ---返回bool類型
data['is_leap_year'] = [tmp.is_leap_year for tmp in data.loc[:, 'time_list']]
print('data:\n', data)

dt屬性
Pandas還有dt屬性可以提取時(shí)間屬性。
data['year'] = data.loc[:, 'time_list'].dt.year
data['month'] = data.loc[:, 'time_list'].dt.month
data['day'] = data.loc[:, 'time_list'].dt.day
print('data:\n', data)

計(jì)算時(shí)間間隔
# 計(jì)算時(shí)間間隔!
ret = pd.to_datetime('2022-3-9 10:08:00') - pd.to_datetime('2022-3-8')
print(ret) # 1 days 10:08:00
print(type(ret)) # <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
print(ret.days) # 1
計(jì)算時(shí)間推移
配合Timedelta()方法可計(jì)算時(shí)間推移
Timedelta 中支持的參數(shù) weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds
res = pd.to_datetime('2022-3-9 10:08:00') + pd.Timedelta(weeks=5)
print(res) # 2022-04-13 10:08:00
print(type(res)) # <class 'pandas._libs.tslibs.timestamps.Timestamp'>
print(pd.Timedelta(weeks=5)) # 35 days 00:00:00
獲取當(dāng)前機(jī)器的支持的最大時(shí)間和 最小時(shí)間
# 獲取當(dāng)前機(jī)器的支持的最大時(shí)間和 最小時(shí)間
print('max :',pd.Timestamp.max)
print('min :',pd.Timestamp.min)
"""
max : 2262-04-11 23:47:16.854775807
min : 1677-09-21 00:12:43.145225
"""
總結(jié)
到此這篇關(guān)于Pandas時(shí)間數(shù)據(jù)處理的文章就介紹到這了,更多相關(guān)Pandas時(shí)間數(shù)據(jù)處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在Python中將字符串轉(zhuǎn)換為數(shù)組詳解
最近在用Python,做一個小腳本,有個操作就是要把內(nèi)容換成數(shù)組對象再進(jìn)行相關(guān)操作,下面這篇文章主要給大家介紹了關(guān)于如何在Python中將字符串轉(zhuǎn)換為數(shù)組的相關(guān)資料,需要的朋友可以參考下2022-12-12
Pytorch中如何調(diào)用forward()函數(shù)
這篇文章主要介紹了Pytorch中如何調(diào)用forward()函數(shù)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
python實(shí)現(xiàn)發(fā)送和獲取手機(jī)短信驗(yàn)證碼
這篇文章主要介紹了python實(shí)現(xiàn)發(fā)送和獲取手機(jī)短信驗(yàn)證碼的相關(guān)資料,講解了python如何解決接口測試獲取手機(jī)驗(yàn)證碼問題,感興趣的小伙伴們可以參考一下2016-01-01
Python中實(shí)現(xiàn)定時(shí)任務(wù)詳解
這篇文章主要介紹了Python中實(shí)現(xiàn)定時(shí)任務(wù)詳解的相關(guān)資料,需要的朋友可以參考下2023-07-07
Python使用Beautiful Soup實(shí)現(xiàn)解析網(wǎng)頁
在這篇文章中,我們將介紹如何使用 Python 編寫一個簡單的網(wǎng)絡(luò)爬蟲,以獲取并解析網(wǎng)頁內(nèi)容。我們將使用 Beautiful Soup 庫,它是一個非常強(qiáng)大的庫,用于解析和操作 HTML 和 XML 文檔。讓我們開始吧2023-05-05
Python解析json文件相關(guān)知識學(xué)習(xí)
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。接下來通過本文給大家介紹python解析json文件相關(guān)知識,對python解析json文件相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2016-03-03

