Hah*_*pro 5 python datetime datetime-format pandas vaex
我有日期字符串(例如:3/24/2020),我想将其转换为datetime64[ns]格式
df2['date'] = pd.to_datetime(df1["str_date"], format='%m/%d/%Y')
Run Code Online (Sandbox Code Playgroud)
在 vaex dataframe 上使用 pandasto_datetime会导致错误:
ValueError: time data 'str_date' does not match format '%m/%d/%Y' (match)
Run Code Online (Sandbox Code Playgroud)
我看到可能有重复的问题。
df2['pdate']=df2.date.astype('datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)
然而,答案是类型转换。我的情况需要将格式('%m/%d/%Y')解析字符串为datetime64[ns],而不仅仅是类型转换。
解决方案:自定义函数,然后.apply
vaex可以使用apply函数进行对象操作,因此您可以使用datetime并np.datetime64转换每个日期字符串,然后应用它。
import numpy as np
from datetime import datetime
def convert_to_datetime(date_string):
return np.datetime64(datetime.strptime(str(date_string), "%Y%m%d%H%M%S"))
df['date'] = df.date.apply(convert_to_datetime)
Run Code Online (Sandbox Code Playgroud)