網站首頁 編程語言 正文
將int轉換成datetime格式
原始時間格式
users['timestamp_first_active'].head()
原始結果:
0 20090319043255
1 20090523174809
2 20090609231247
3 20091031060129
4 20091208061105
Name: timestamp_first_active, dtype: object
錯誤的轉換
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轉換成str ,再轉成時間:
users['timestamp_first_active']=users['timestamp_first_active'].astype('str')
users['timestamp_first_active']=pd.to_datetime(users['timestamp_first_active'])
pandas 時間數據處理
轉化時間類型
to_datetime()方法
to_datetime()方法支持將 int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like 類型的數據轉化為時間類型
import pandas as pd
# str ---> 轉化為時間類型:
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中默認支持的時間點的類型
"""
# 字符串的序列 --->轉化成時間類型:
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中的時間數據類型!
DatetimeIndex()方法
DatetimeIndex()方法支持將一維 類數組( array-like (1-dimensional) )轉化為時間序列
# pd.DatetimeIndex 將 字符串序列 轉化為 時間序列
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()方法可以生成時間序列。
時間序列一般不會主動生成,往往是在發生某個事情的時候,同時記錄一下發生的時間!
ret = pd.date_range(
start='2021-10-1', # 開始點
# end='2022-1-1', # 結束點
periods=5, # 生成的元素的個數 和結束點只需要出現一個即可!
freq='W', # 生成數據的步長或者頻率, W表示Week(星期)
)
print(ret)
"""
DatetimeIndex(['2021-10-03', '2021-10-10', '2021-10-17', '2021-10-24', '2021-10-31'],
dtype='datetime64[ns]', freq='W-SUN')
"""
提取時間屬性
使用如下數據作為初始數據(type:<class ‘pandas.core.frame.DataFrame’>):
# 轉化為 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 中支持的參數 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
"""
原文鏈接:https://blog.csdn.net/qq_39817865/article/details/108848346
相關推薦
- 2022-06-25 Gitlab-runner+Docker實現自動部署SpringBoot項目_docker
- 2022-05-12 databinding 與 RecyclerView.Adapter
- 2022-08-20 pip安裝路徑修改的詳細方法步驟_python
- 2021-12-16 jquery+swiper組件實現時間軸滑動年份tab切換效果_jquery
- 2023-01-12 Android?RecyclerChart其它圖表繪制示例詳解_Android
- 2023-03-04 Golang中goroutine和channel使用介紹深入分析_Golang
- 2022-08-17 WPF中的導航框架概述_C#教程
- 2022-06-10 ASP.NET?Core使用EF保存數據、級聯刪除和事務使用_實用技巧
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支