Pandas之object字符类型转时间类型to_datetime()函数

一、pandas中to_datetime()函数

可以将指定数据转换为相应格式的时间类型数据
pandas.to_datetime(arg,format=None,unit=None)

参数 含义
arg 需要转换类型的数据
format 所输入数据的时间格式
unit 最小时间间隔,如’D’代表一天

二、函数实例

  1. 将dataframe数据框中object型数据转换为datetime型数据
#原数据
filedf['pub_date'].head()
>>>
0    10/20/2018 13:48:08
1    10/19/2018 13:52:30
2    10/20/2018 14:53:58
3    10/18/2018 20:01:24
4    10/18/2018 16:58:32
Name: pub_date, dtype: object

#将object型数据转为相应类型的datetime64型数据
filedf['pub_date2']=pd.to_datetime(filedf['pub_date'],format='%m/%d/%Y %H:%M:%S')
filedf['pub_date2'].head()
>>>
0   2018-10-20 13:48:08
1   2018-10-19 13:52:30
2   2018-10-20 14:53:58
3   2018-10-18 20:01:24
4   2018-10-18 16:58:32
Name: pub_date2, dtype: datetime64[ns]
  1. datetime型与object型数据相互转换
    to_datetime():datetime转为object
    strftime():object转为datetime
#原数据
df = pd.DataFrame({'year': [2015, 2016],'month': [2, 3],'day': [4, 5]})
print(df)
>>>
   year  month  day
0  2015      2    4
1  2016      3    5

#将指定数据转为相应类型的datetime64型数据
df['df_time']=pd.to_datetime(df)
print(df)
>>>
   year  month  day    df_time
0  2015      2    4 2015-02-04
1  2016      3    5 2016-03-05

#将时间型转为字符型
df_object=df_time.map(lambda x:x.strftime('%Y/%m/%d'))
print(df_object)
>>>
0    2015/02/04
1    2016/03/05
dtype: object
  1. 求时间类型数据的周期
#weekday_name属性是针对元素级进行操作的,所以这里利用map函数
df['weekday']=df['df_time'].map(lambda x:x.weekday_name)
print(df)
>>>
   year  month  day    df_time    weekday
0  2015      2    4 2015-02-04  Wednesday
1  2016      3    5 2016-03-05   Saturday

更多常用时间

猜你喜欢

转载自blog.csdn.net/MsSpark/article/details/83352891
今日推荐