Fernanda
Fernanda

Reputation: 35

Pandas: Change object to Date_time

I'm learning Pandas and I have a problem trying to change a format from Object to Date_time.

When I use 'to_datetime' the date I get in return is like in ISO Format, and I just want DD/MM/YYYY (13/10/1960). And I doing something wrong? Thanks a lot!!

enter image description here

Upvotes: 1

Views: 272

Answers (1)

Willy Chang
Willy Chang

Reputation: 51

At a glance, it doesn't seem like the code uses the right format.

The to_datetime() with the format argument follows strftime standards per the documentation here, and it's a way to tell the method how the original time was represented (so it can properly format it into a datetime object). An example can be seen from this Stack Overflow question.

Simple example: datetime_object = pd.to_datetime(format='%d/%m/%Y')

The next problem is how you want that datetime object to be printed out (i.e. DD/MM/YYYY). Just throwing thoughts out there (would comment, but I don't have those privileges yet), if you want to print the string, you can cast that datetime object into the string that you want. Many ways to do this, one of which is to use strftime().

Simple example: date_as_string = datetime_object.strftime('%d/%m/%Y')

But of course, why would you use a datetime object in that case. So the other option I can think of is to override how the datetime object is printed (redefining __str__ in a new class of datetime).

Upvotes: 1

Related Questions