[英]Convert DataFrame column from string to datetime for format "January 1, 2001 Monday"
I am trying to convert a dataframe column " date " from string
to datetime
.我正在尝试将 dataframe 列“日期”从
string
转换为datetime
时间。 I have this format: " January 1, 2001 Monday ".我有这样的格式:“ 2001 年 1 月 1 日,星期一”。
I tried to use the following:我尝试使用以下内容:
from dateutil import parser
for index,v in df['date'].items():
df['date'][index] = parser.parse(df['date'][index])
But it gives me the following error:但它给了我以下错误:
ValueError: Cannot set non-string value '2001-01-01 00:00:00' into a StringArray.
I checked the datatype of the column " date " and it tells me string
type.我检查了“日期”列的数据类型,它告诉我
string
类型。
This is the snippet of the dataframe:这是 dataframe 的片段:
Any help would be most appreciated!非常感激任何的帮助!
You need to specify the format for the datetime
object in order it to be parsed correctly.您需要指定
datetime
时间 object 的格式才能正确解析它。 The documentation helps with this:该文档有助于此:
%A
is for Weekday as locale's full name, eg, Monday %A
代表工作日,作为语言环境的全名,例如,Monday%B
is for Month as locale's full name, eg, January %B
代表月份作为语言环境的全名,例如 January%d
is for Day of the month as a zero-padded decimal number. %d
是一个月中的第几天作为零填充的十进制数。%Y
is for Year with century as a decimal number, eg, 2021. %Y
代表年份,世纪为十进制数,例如 2021。 Combining all of them we have the following function:结合所有这些我们有以下 function:
from datetime import datetime
def mdy_to_ymd(d):
return datetime.strptime(d, '%B %d, %Y %A').strftime('%Y-%m-%d')
print(mdy_to_ymd('January 1, 2021 Monday'))
> 2021-01-01
One more thing is for your case, .apply()
will work faster, thus the code is:对于您的情况还有一件事,
.apply()
会更快地工作,因此代码是:
df['date'] = df['date'].apply(lambda x: mdy_to_ymd)
Feel free to add Hour-Minute-Second if needed.如果需要,请随意添加小时-分钟-秒。
why don't you try this instead of dateutils
, pandas
offer much simpler tools such as pd.to_datetime
function:你为什么不试试这个而不是
dateutils
, pandas
提供了更简单的工具,例如pd.to_datetime
function:
df['date'] = pd.to_datetime(df['date'], format='%B %d, %Y %A')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.