I have the data like this
df['Date']=['05.01.2017','05.01.2017']
I tried
df1= pd.to_datetime(df['Date'])
but it turned a bad result
Id like to get the new data like this
result=[05-01-2017,05-01-2017]
I have the data like this
df['Date']=['05.01.2017','05.01.2017']
I tried
df1= pd.to_datetime(df['Date'])
but it turned a bad result
Id like to get the new data like this
result=[05-01-2017,05-01-2017]
You just need to specify the format of the dates in your column. This works for me from your example. Simple.
pd.to_datetime(df['Date'], format = '%d.%m.%Y')
I'm assuming that the numbers in your dates are day.month.year respectively and not month.day.year. If the latter is true then you should use format = '%m.%d.%Y'
instead.
If you know your dates are always going to be strings in the form of MM.DD.YYYY, and you just wand MM-DD-YYYY instead, then you don't have to deal with any datetime
conversions. You can just do a substitution on the string:
>>> from datetime import datetime
>>> mydatestrings = ['05.01.2017','05.02.2017','05.03.2017']
>>> newdates = [ d.replace('.','-') for d in mydatestrings ]
>>> print(newdates)
['05-01-2017', '05-02-2017', '05-03-2017']
On the other hand, if you really want to get all of your dates as 'datetime' objects in Python, you can make a new list like this:
>>> datetime_objs = [ datetime.strptime(d, '%m.%d.%Y') for d in mydatestrings ]
Then format it however you need to:
>>> print(datetime_objs[1].strftime('%m-%d-%Y'))
05-02-2017
>>> print(datetime_objs[1].strftime('%b, %d %Y'))
May, 02 2017