Python使用for循环将多列转换为datetime

Python使用for循环将多列转换为datetime,python,pandas,function,datetime,for-loop,Python,Pandas,Function,Datetime,For Loop,我被困在这上面,正在寻求社区帮助。我在dataframe中有一些列标记为对象,但希望转换为datetime。所有列都有年、月、日标准 time = np.array(['time1','time2','time3']) 虽然都有年、月、日我收到这个错误 ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing df-

我被困在这上面,正在寻求社区帮助。我在dataframe中有一些列标记为对象,但希望转换为datetime。所有列都有年、月、日标准

time = np.array(['time1','time2','time3'])
虽然都有年、月、日我收到这个错误

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing
df-

df中可能存在需要跳过的空值

我在没有他们的情况下做了测试,运气也不好。所以我不太清楚为什么这种方法不起作用。谢谢

您可以使用

将熊猫作为pd导入
def转换时间(df,cols=None):
如果不是cols:
#如果未指定任何列,请使用“全部”
cols=df.columns
df[cols]=df[cols].astype('datetime64')
返回df
df=pd.DataFrame({
“创建时间:['2020-06-06 20:01:10.327'],
“更新地址:['2020-06-06 22:08:14.832']
})
打印(df.dtypes)
#在对象上创建
#在对象上更新了\u
#数据类型:对象
df2=转换时间(df)
打印(df2.D类型)
#已在datetime64创建\u[ns]
#更新日期时间64[ns]
#数据类型:对象
您可以使用

将熊猫作为pd导入
def转换时间(df,cols=None):
如果不是cols:
#如果未指定列,请使用全部
cols=df.columns
df[cols]=df[cols].astype('datetime64')
返回df
df=pd.DataFrame({
“创建时间:['2020-06-06 20:01:10.327'],
“更新地址:['2020-06-06 22:08:14.832']
})
打印(df.dtypes)
#在对象上创建
#在对象上更新了\u
#数据类型:对象
df2=转换时间(df)
打印(df2.D类型)
#已在datetime64创建\u[ns]
#更新日期时间64[ns]
#数据类型:对象

请发布一个DataFrameWare示例,使用
时间
等变量名。。。另外,它将是数据特定的。我添加了一个简化的df样本。请发布一个DataFrameWare的示例,使用
time
作为变量名。。。另外,它将是数据特定的。我添加了一个简化的df样本。如果其中一个df没有所有的列,我怎么能轻松地解释呢?你的意思是说,在这种情况下,你的数据帧有很多列,但你只想将其中的一个子集制作成datetime?使用
转换时间(df,['col1','col2'])
。如果一个df只有time1,而另一个df有time1、time2、time3,则数据帧的所有其他列都不会被触动。我在一些dfs上运行此操作,因此如果不是所有时间列都在DFT中,则会出现not in index错误,此时您必须使用
convert_times(df1,['time1','time2']);convert_times(df2,['anothertime1','anothertime2'])
如果其中一个dfs没有所有的列,我如何轻松地解释这一点?您的意思是,您的数据帧有很多列,但您只想将其中的一个子集转换为datetime?使用
转换时间(df,['col1','col2'])
。如果一个df只有time1,而另一个df有time1、time2、time3,则数据帧的所有其他列都不会被触动。我在一些dfs上运行此操作,因此如果不是所有时间列都在DFT中,则会出现not in index错误,此时您必须使用
convert_times(df1,['time1','time2']);转换时间(df2,['anothertime1','anothertime2'])
ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing
time1                      time2                      time3 
2020-06-06 20:01:10.327    2020-06-06 22:08:14.832    2020-06-06