在用pandas处理数据时,经常要处理一些时间类型数据,经常把pandas时间类型与datetime模块,还有python自带的time模块搞混淆,记录之。
unix 时间戳与pandas中的Timestamp互转:
import time
def unixToTime(unixtime):
return pd.to_datetime(unixtime,unit='s',utc=True).tz_convert('Asia/Shanghai') #utc时间比上海时间少8小时,做时区转换
def timeToUnix(dt64):
return dt64.astype('datetime64[s]').astype('int')
unixtime = 1514737265
print(unixToTime(unixtime))
#python 自带time模块的local_time可以直接转北京时间
struct_time = time.localtime(unixtime)
print(struct_time)
#转化格式
dd = time.strftime("%Y-%m-%d %H:%M:%S",struct_time)
print(dd)
输出:
2018-01-01 00:21:05+08:00
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=21, tm_sec=5, tm_wday=0, tm_yday=1, tm_isdst=0)
2018-01-01 00:21:05
datetime模块
python中还有一个datetime模块,这个模块包含一些函数,如today,now,fromtimestamp,strptime,Datetime
from datetime import datetime
import pandas as pd
startTime = datetime.now()
print(startTime)
print(type(startTime))
#datetime 字符串转时间戳
timestr = '2018-01-01 00:21:05'
date_time = datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S")
print(type(date_time))
print(date_time)
输出:
2020-12-16 22:22:42.451086
<class 'datetime.datetime'>
#pandas 字符串转时间戳
pd_time = pd.to_datetime(time,format="%Y-%m-%d %H:%M:%S")
#或者
#time = datetime(2018,1,1,0,21,5)
#pd_time = pd.to_datetime(timestr,format="YYYY-MM-DD HH:MM:SS")
print(type(pd_time))
print(pd_time)
输出:
<class 'datetime.datetime'>
2018-01-01 00:21:05
#取到年,月,日,日期,小时,分钟,秒以及一周中的第几天
year = pd_time.year
month = pd_time.month
day = pd_time.day
date = pd_time.date
hour = pd_time.hour
minute = pd_time.minute
seconds = pd_time.second
print(year)
print(month)
print(day)
print(hour)
print(minute)
print(seconds)
输出:
2018
1
1
0
21
5
参考:
https://www.cnblogs.com/haitaoli/p/10823403.html(强烈推荐)
https://blog.csdn.net/sunjinjuan/article/details/79090521
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html(pandas官方文档)