1

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]

Evan
  • 2,121
  • 14
  • 27
Dr. know
  • 107
  • 2
  • 4

2 Answers2

1

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.

James Fulton
  • 322
  • 2
  • 8
  • I'm not so sure. My _guess_ is that they want to convert back to a string because this would not result in a natural representation that's useful for much. I think it's an XY problem. – roganjosh Nov 14 '18 at 21:43
  • I think since the desired `result=[05-01-2017,05-01-2017]` and there are no string marks around the result dates like there was around the input dates, that they want it in datetime format. However, I shall wait for their response. – James Fulton Nov 14 '18 at 21:46
  • Think you're right on that. Can't test atm so I think it relies on clarification from OP on what exactly they intend. – roganjosh Nov 14 '18 at 21:50
  • thanks James for your clarification – Dr. know Nov 14 '18 at 22:14
0

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
Bill M.
  • 1,388
  • 1
  • 8
  • 16