首页 > 脚本专栏 > python > pandas将int转换成datetime格式

pandas时间序列之如何将int转换成datetime格式

作者:qq_39817865

这篇文章主要介绍了pandas时间序列之如何将int转换成datetime格式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

将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)

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
  • Python实现多元线性回归的梯度下降法
    Python实现多元线性回归的梯度下降法
    2022-08-08
  • Python实现单例模式的五种写法总结
    Python实现单例模式的五种写法总结
    2022-08-08
  • Python实现图片格式转换小程序
    Python实现图片格式转换小程序
    2022-08-08
  • pytest文档内置fixture的request详情
    pytest文档内置fixture的request详情
    2022-08-08
  • python 中pass和match使用方法
    python 中pass和match使用方法
    2022-08-08
  • numpy中数组拼接、数组合并方法总结(append(), concatenate, hstack, vstack, column_stack, row_stack, np.r_, np.c_等)
    numpy中数组拼接、数组合并方法总结(append(), concate
    2022-08-08
  • numpy拼接矩阵的实现
    numpy拼接矩阵的实现
    2022-08-08
  • 关于pyqt5弹出提示框的详细介绍
    关于pyqt5弹出提示框的详细介绍
    2022-08-08
  • 美国设下计谋,用娘炮文化重塑日本,已影响至中国
    美国设下计谋,用娘炮文化重塑日本,已影响至中国
    2021-11-19
  • 时空伴随者是什么意思?时空伴随者介绍
    时空伴随者是什么意思?时空伴随者介绍
    2021-11-09
  • 工信部称网盘企业免费用户最低速率应满足基本下载需求,天翼云盘回应:坚决支持,始终
    工信部称网盘企业免费用户最低速率应满足基本下载需求,天翼云盘回应:坚决支持,始终
    2021-11-05
  • 2022年放假安排出炉:五一连休5天 2022年所有节日一览表
    2022年放假安排出炉:五一连休5天 2022年所有节日一览表
    2021-10-26
  • 电脑版 - 返回首页

    2006-2023 脚本之家 JB51.Net , All Rights Reserved.
    苏ICP备14036222号