时刻数据代表时间点,是pandas的数据类型,是将值与时间点相关联的最基本类型的时间序列数据
from datetime import datetime
import pandas as pd
date1 = datetime(2016, 12, 1, 12, 45, 30) # 创建一个datetime.datetime
date2 = '2017-12-21' # 创建一个字符串
data3 = '2017-12-21 15:00:22'
# 直接生成pandas的时刻数据 → 时间戳【数据类型为pandas的Timestamp】
t1 = pd.Timestamp(date1)
t2 = pd.Timestamp(date2)
t3 = pd.Timestamp(data3)
print("t1 = {0}, type(t1) = {1}".format(t1, type(t1)))
print("t2 = {0}, type(t2) = {1}".format(t2, type(t2)))
print("t3 = {0}, type(t3) = {1}".format(t3, type(t3)))
打印结果:
t1 = 2016-12-01 12:45:30, type(t1) = <class 'pandas._libs.tslibs.timestamps.Timestamp'>
t2 = 2017-12-21 00:00:00, type(t2) = <class 'pandas._libs.tslibs.timestamps.Timestamp'>
t3 = 2017-12-21 15:00:22, type(t3) = <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Process finished with exit code 0
pd.to_datetime():
pd.to_datetime():如果输入是单个时间数据,转换成pandas的时刻数据,数据类型为Timestamp
from datetime import datetime
import pandas as pd
# pd.to_datetime():如果是单个时间数据,转换成pandas的时刻数据,数据类型为Timestamp
date1 = datetime(2016, 12, 1, 12, 45, 30)
date2 = '2017-12-21'
t1 = pd.to_datetime(date1)
t2 = pd.to_datetime(date2)
print("t1 = {0}, type(t1) = {1}".format(t1, type(t1)))
print("t2 = {0}, type(t2) = {1}".format(t2, type(t2)))
print('-' * 100)
打印结果:
t1 = 2016-12-01 12:45:30, type(t1) = <class 'pandas._libs.tslibs.timestamps.Timestamp'>
t2 = 2017-12-21 00:00:00, type(t2) = <class 'pandas._libs.tslibs.timestamps.Timestamp'>
Process finished with exit code 0
将时间字符串转化成时间戳分为两步:
import time
data['timestamp'] = data['OCC_TIM'].apply(lambda x:time.mktime(time.strptime(x,'%Y-%m-%d %H:%M:%S')))
其中,strptime函数是将字符串按照后面的格式转换成时间元组类型;mktime函数则是将时间元组转换成时间戳。
a = “2013-10-10 23:40:00” ,想改为 a = “2013/10/10 23:40:00”
方法:先转换为时间数组,然后转换为其他格式
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S" )
otherStyleTime = time.strftime( "%Y/%m/%d %H:%M:%S" , timeArray)
timeArray = time.strptime(a, "%Y%m%d%H%M%S" )
otherStyleTime = time.strftime( "%Y-%m-%d %H:%M:%S" , timeArray)
pandas的
pd_file['timestamp'] = pd_file['时间'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(str(x),'%Y%m%d%H%M%S')))
参考资料:
【学习经典】时间序列处理(DatetimeIndex)
pandas实现将日期转换成timestamp
Python对DataFrame的 日期时间的处理
python 时间字符串和时间戳之间的转换
pandas实现将日期转换成timestamp
使用pandas怎么将日期转换成timestamp