【发布时间】:2020-03-14 16:28:13
【问题描述】:
我想将pandas中的字符串转换为日期时间,但转换失败。
我的数据格式例如 06.12.2015 这意味着日.月.年
try:
#Code that may raise an error
df['date']= pd.to_datetime(df['date'], format='%d%m%Y')
#Raising your own errors
raise Exception("Error converting date")
except Exception as e:
#code to run if error occurs
logging.error("Exception occurred " + filename , exc_info=True)
#code to run if error is raised
print("Conversion not work.")
else:
df['date']= pd.to_datetime(df['date'], format='%d.%m.%y')
然后
print(df.dtypes)
给出对象并引发异常。
有人可以帮帮我吗?
【问题讨论】:
-
你可以用
''替换.:pd.to_datetime(s.str.replace('.',''), format='%d%m%Y'),用s = pd.Series(['06.12.2015','06122015'])测试然后pd.to_datetime(s.str.replace('.',''), format='%d%m%Y') -
我没有一个系列,而是一个表格列,其日期格式为 11.02.1984 ,解决方案会是什么样子
-
表格列?那不是一个系列吗?将
s替换为table['column'] -
df['date']=pd.to_datetime(df['date'],format='%d.%m.%Y')!!! -
你能创建一个“reprex”吗? stackoverflow.com/help/minimal-reproducible-example