![v2-37f2fc637b92ac28da5c2383873a541a_1440w.jpg?source=172ae18b](http://img-02.proxy.5ce.com/view/image?&type=2&guid=4be71e17-c52f-eb11-8da9-e4434bdf6706&url=https://pic4.zhimg.com/v2-37f2fc637b92ac28da5c2383873a541a_1440w.jpg?source=172ae18b)
在数据分析的过程中,经常面临各种时间获取,类型转换的问题;本文主要讲解 Python语言中 时间类型之间的转换,以及pandas中的时间处理。
1 标准时间处理库
Python 标准库中有两个处理时间的库。其中一个名为 datetime
,另一个是time
。
在 Python 官网文档中,datetime 是被定义为数据类型(Data Types)。由此可见,datetime 是主要提供处理日期和时间的数据类型的模块。它其中有几个常用的类型,例如:datetime.datetime、datetime.time、datetime.date 等,其中最主要的类是datetime.datetime
。因为它携带了 datetime.time 和 datetime.date 这两个所带的信息,能够比较齐全地输出,即能一次性就输出年、月、日、时、分、秒等日期和时间信息。
time 模块是归属于通用操作系统服务(Generic Operating System Services)类目中。time 模块主要提供各种时间转换的函数。它服务于系统层次,Python 又是跨平台的,所以有些 API 只能在某些操作系统上使用。
1.1 时间对象类型
在 Python 中,涉及时间对象有 4 种:
1)datetime
2)timestamp
3)time tuple
4)string
1.2 类型转换及代码
现实中会经常遇到 datetime <--> string的相互转换,主要通过strftime, strptime函数来完成。
import datetime
# return datetime类型
now = datetime.datetime.now()
print(now)
print(type(now))
"""
>> 2019-12-02 15:22:35.176142
>> <class 'datetime.datetime'>
"""
# datetime 转 string
str_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(str_now)
"""
>> '2019-12-02 14:40:35'
"""
# string 转 datetime
t1 = '2019-12-02 14:40:35'
t2 = datetime.datetime.strptime(t1, "%Y-%m-%d %H:%M:%S")
print(t2)
print(type(t2))
"""
>> 2019-12-02 14:40:35
>> <class 'datetime.datetime'>
"""
timestamp 指的是 Unix 时间戳。它是格林威治时间 1970 年 01 月 01 日 00 时 00 分 00 秒(北京时间 1970 年 01 月 01 日 08 时 00 分 00 秒)起至现在的总秒数。我们使用 time 对象中的time()函数能获取到时间戳
import time
# 通过time库 获取当前时间戳
now_timestamp = time.time()
print(now)
print(type(now))
"""
>> 1575272037.5272005
>> <class 'float'>
"""
now_tuple = time.localtime()
print(now_tuple )
print(type(now_tuple))
"""
>> time.struct_time(tm_year=2019, tm_mon=12, tm_mday=2, tm_hour=14, tm_min=42, tm_sec=44, tm_wday=0, tm_yday=336, tm_isdst=0)
>> <class 'time.struct_time'>
"""
1.3 类型转换图
- 类型转换主要上前辈整理的示意图
![v2-a595f5ef34a46513efb7123802082843_b.jpg](http://img-02.proxy.5ce.com/view/image?&type=2&guid=4be71e17-c52f-eb11-8da9-e4434bdf6706&url=https://pic4.zhimg.com/v2-a595f5ef34a46513efb7123802082843_b.jpg)
2 pandas中时间数据类型转换
实际工作中我们通常使用pandas来进行数据的读取,分析等;因此,对于pandas中的时间对象类型 与 Python时间对象的转换也要十分清楚。
可以通过pandas中to_datetime函数进行时间数据类型转换
![v2-ab3fd07e844adc2e05295cadb6078997_b.jpg](http://img-03.proxy.5ce.com/view/image?&type=2&guid=4be71e17-c52f-eb11-8da9-e4434bdf6706&url=https://pic4.zhimg.com/v2-ab3fd07e844adc2e05295cadb6078997_b.jpg)
后续,可以通过dataframe 时间序列索引的方式去 获取,处理数据。
参考文档:极客猴:Python 中各种时间类型的转换zhuanlan.zhihu.com
![v2-beaa05d05af668f3736f1740476bda85_180x120.jpg](http://img-03.proxy.5ce.com/view/image?&type=2&guid=4be71e17-c52f-eb11-8da9-e4434bdf6706&url=https://pic2.zhimg.com/v2-beaa05d05af668f3736f1740476bda85_180x120.jpg)