pandas strptime() 参数 1 必须是 str,而不是系列时间序列转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50109695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:31:05  来源:igfitidea点击:

strptime() argument 1 must be str, not Series time series convert

pythonpandasdatetime

提问by qing zhangqing

I use datetime to read time from json, the code for single time works well,

我使用 datetime 从 json 中读取时间,单个时间的代码运行良好,

 import datetime
 data=datetime.datetime.strptime('Apr 12, 2018', '%b %d, Y').strftime('%m/%d/%Y')

However, when I try to apply it into data frame, I have error.

但是,当我尝试将其应用到数据框中时,出现错误。

 df_newtime=datetime.datetime.strptime(old_df['oldDate'],'%b %d, %Y').strftime('%m/%d/%Y')

the error is TypeError: strptime() argument 1 must be str, not Series

错误是 TypeError: strptime() argument 1 must be str, not Series

采纳答案by YOLO

You can do it in two ways:

你可以通过两种方式做到这一点:

Method 1:

方法一:

Here we pass a string to the function using map

这里我们使用一个字符串传递给函数 map

list(map(lambda x: datetime.datetime.strptime(x,'%b %d, %Y').strftime('%m/%d/%Y'), old_df['oldDate']))

Method 2:

方法二:

Here we pass a series

这里我们通过一个系列

pd.to_datetime(old_df['oldDate'], format='%b %d, %Y')

回答by sakurashinken

old_df['oldDate']will return the column containing the dates, which is a series.

old_df['oldDate']将返回包含日期的列,这是一个系列。

You can solve this issue by using the .apply function in pandas to apply a function to every row of a dataframe. See here

您可以通过使用 pandas 中的 .apply 函数将函数应用于数据帧的每一行来解决此问题。看这里

def date_convert(date_to_convert):
     return datetime.datetime.strptime(date_to_convert, '%b %d, 
     %Y').strftime('%m/%d/%Y')

new_df['new_date'] = old_df['oldDate'].apply(date_convert)