简体   繁体   English

需要将整个列从字符串格式转换为数据帧中的日期格式

[英]Need to convert entire column from string format to date format from a Dataframe

I am trying to convert an entire column from a Dataframe from a string to date format. 我正在尝试将数据框的整个列从字符串转换为日期格式。 Does anyone have any recommendations on how to do this? 是否有人对此有任何建议?

I've successfully been able to change one element of this using strptime, but not sure the best way to apply this to the entire column: 我已经能够使用strptime成功更改其中的一个元素,但是不确定将其应用于整个列的最佳方法:

Sample of the raw Data: 原始数据样本:

2016/06/28 02:13:51

In: 在:

Var1 = Dataframename['columnname'][0]
temp = datetime.datetime.strptime(Var1, '%Y/%m/%d  %H:%M:%S')
temp

Out: 日期:

datetime.datetime(2016, 6, 28, 2, 13, 51)

I think you are looking for this 我想你在找这个

import datetime
data['colname']=data['colname'].apply(lambda x:datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S"))

You can use to_datetime : 您可以使用to_datetime

df = pd.DataFrame({'b':['2016/06/28 02:13:51','2016/06/28 02:13:51','2016/06/28 02:13:51'],
                   'a':[4,5,6]})

print (df)
   a                    b
0  4  2016/06/28 02:13:51
1  5  2016/06/28 02:13:51
2  6  2016/06/28 02:13:51

df['b'] = pd.to_datetime(df.b)
print (df)
   a                   b
0  4 2016-06-28 02:13:51
1  5 2016-06-28 02:13:51
2  6 2016-06-28 02:13:51
print (df.dtypes)
a             int64
b    datetime64[ns]
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将时间戳从 dataframe 列转换为日期格式 - Convert timestamps from a dataframe column to date format 使用python将DataFrame列日期从2/3/2007格式转换为20070223 - Convert DataFrame column date from 2/3/2007 format to 20070223 with python 在 Pandas 数据框中将列类型从字符串转换为日期时间格式 - Convert the column type from string to datetime format in Pandas dataframe Dataframe 具有不同格式的日期值的字符串列。 如何将整列数据转换为单个日期格式? - Dataframe has string column with date values in different formats. how to convert entire column data to single date format? 将 DataFrame 列从字符串转换为日期时间格式“2001 年 1 月 1 日星期一” - Convert DataFrame column from string to datetime for format "January 1, 2001 Monday" 将日期转换为整个新列的不同格式 - Convert a date to a different format for an entire new column 从UTC格式转换为字符串的日期 - Convert from String to Date from UTC format 将字符串列直接转换为 Pandas DataFrame 中的日期格式(不是日期时间) - Convert String Column directly to Date format (not Datetime) in Pandas DataFrame 将数据框列的值从整数格式化为字符串 - Format the values of a dataframe column from integer to string 如何在python中从字符串格式转换日期 - How to convert date from string format in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM