我想将字符串“17.07.2019”转换为日期格式 17-07-2019(或 17-Jul-2019)
我试过这段代码
from datetime import datetime
x = '17.07.2019'
y=datetime.strptime(x,'%d.%m.%y')
y=datetime.strftime(x,'%d.%m.%y')
但是我得到了这个错误
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
然后我尝试了
y=pd.to_datetime(x,'%d.'%m.%Y')
但是我得到了这个错误
SyntaxError: invalid syntax
最佳答案
对于这么简单的事情,您可以只使用 str.replace
。
y = x.replace('.', '-')
或者要修复您的代码,您只需在 y
上使用 strftime
:
y = date.strptime(x, '%d.%m.%Y')
z = y.strftime('%d-%m-%Y')
关于python - 将字符串转换为日期格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332351/