pandas時間序列之如何將int轉(zhuǎn)換成datetime格式
將int轉(zhuǎn)換成datetime格式
原始時間格式
users['timestamp_first_active'].head()
原始結果:
0 20090319043255
1 20090523174809
2 20090609231247
3 20091031060129
4 20091208061105
Name: timestamp_first_active, dtype: object
錯誤的轉(zhuǎn)換
pd.to_datetime(sers['timestamp_first_active'])
錯誤的結果類似這樣:
0 1970-01-01 00:00:00.020201010
1 1970-01-01 00:00:00.020200920
Name: time, dtype: datetime64[ns]
正確的做法
先將int轉(zhuǎn)換成str ,再轉(zhuǎn)成時間:
users['timestamp_first_active']=users['timestamp_first_active'].astype('str')
users['timestamp_first_active']=pd.to_datetime(users['timestamp_first_active'])pandas 時間數(shù)據(jù)處理
轉(zhuǎn)化時間類型
to_datetime()方法
to_datetime()方法支持將 int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like 類型的數(shù)據(jù)轉(zhuǎn)化為時間類型
import pandas as pd
# str ---> 轉(zhuǎn)化為時間類型:
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中默認支持的時間點的類型
"""
# 字符串的序列 --->轉(zhuǎn)化成時間類型:
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中默認支持的時間序列的類型
"""
# dtype = 'datetime64[ns]' ----> numpy中的時間數(shù)據(jù)類型!DatetimeIndex()方法
DatetimeIndex()方法支持將一維 類數(shù)組( array-like (1-dimensional) )轉(zhuǎn)化為時間序列
# pd.DatetimeIndex 將 字符串序列 轉(zhuǎn)化為 時間序列 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'> """
生成時間序列
使用date_range()方法可以生成時間序列。
時間序列一般不會主動生成,往往是在發(fā)生某個事情的時候,同時記錄一下發(fā)生的時間!
ret = pd.date_range(
start='2021-10-1', # 開始點
# end='2022-1-1', # 結束點
periods=5, # 生成的元素的個數(shù) 和結束點只需要出現(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ù)據(jù)作為初始數(shù)據(jù)(type:<class ‘pandas.core.frame.DataFrame’>):

# 轉(zhuǎn)化為 pandas支持的時間序列之后再提取時間屬性! data.loc[:, 'time_list'] = pd.to_datetime(data.loc[:, 'time_list']) # 可以通過列表推導式來獲取時間屬性 # 年月日 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']] # 時分秒 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']] # 時間 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屬性可以提取時間屬性。
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)
計算時間間隔
# 計算時間間隔!
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計算時間推移
配合Timedelta()方法可計算時間推移
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獲取當前機器的支持的最大時間和最小時間
# 獲取當前機器的支持的最大時間和 最小時間
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
"""以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- pandas的to_datetime時間轉(zhuǎn)換使用及學習心得
- python3中datetime庫,time庫以及pandas中的時間函數(shù)區(qū)別與詳解
- pandas時間序列之pd.to_datetime()的實現(xiàn)
- pandas如何將datetime64[ns]轉(zhuǎn)為字符串日期
- Pandas如何將Timestamp轉(zhuǎn)為datetime類型
- pandas實現(xiàn)datetime64與unix時間戳互轉(zhuǎn)
- pandas庫中to_datetime()方法的使用解析
- Python中的Pandas?時間函數(shù)?time?、datetime?模塊和時間處理基礎講解
- Pandas中datetime數(shù)據(jù)類型的使用
相關文章
python中torch可以成功引用但無法訪問屬性的解決辦法
這篇文章給大家介紹了我們在python中運行程序時遇到一個奇怪的報錯,torch可以成功引用但無法訪問屬性,這是比較奇怪的一件事,因為torch肯定是可以訪問Tensor,所以本文給大家介紹了torch可以成功引用但無法訪問屬性的解決辦法,需要的朋友可以參考下2024-01-01
Python內(nèi)置方法實現(xiàn)字符串的秘鑰加解密(推薦)
在Python中實現(xiàn)AES算法需要借助的第三方庫Crypto,其在各個操作系統(tǒng)上的安裝方法有些許復雜,所以對于簡單的使用有點殺雞用牛刀的意思。這篇文章主要介紹了利用Python內(nèi)置方法實現(xiàn)字符串的秘鑰加解密,需要的朋友可以參考下2019-12-12

