zaydar
zaydar

Reputation: 181

Converting a string to a date format?

I would like to convert a string '17.07.2019' to date format 17-07-2019 (or 17-Jul-2019)

I tried this code

from datetime import datetime
x = '17.07.2019'    
y=datetime.strptime(x,'%d.%m.%y')    
y=datetime.strftime(x,'%d.%m.%y')

but I get this error

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

I then tried

y=pd.to_datetime(x,'%d.'%m.%Y')

but I got this error

SyntaxError: invalid syntax

Upvotes: 1

Views: 60

Answers (2)

exiz
exiz

Reputation: 93

strftime is used to convert datetime to str, strptime is used to convert str to datetime.

This is what you need:

from datatime import datetime as date
x = '17.07.2019'
y = date.strptime(x, '%d.%m.%Y')
new_format = y.strftime('%d-%m-%Y')

you also can convert to the new format directly

new_format = date.strptime('17.07.2019', '%d.%m.%Y').strftime('%d-%m-%Y')

Upvotes: 1

Jab
Jab

Reputation: 27485

You could just use str.replace for something this simple.

y = x.replace('.', '-')

Or to fix your code you need to just use strftime on y:

y = date.strptime(x, '%d.%m.%Y')
z = y.strftime('%d-%m-%Y')

Upvotes: 3

Related Questions