Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas to_datetime is not formatting the datetime value in the desired format (dd/mm/YYYY HH:MM:SS AM/PM)

I have the datetime values in the following format

    2017-09-11 01:18:38
    2017-09-11 01:34:30
    2017-09-11 05:03:57
    2017-09-11 09:55:48
    2017-09-11 09:59:10
    2017-09-11 12:09:05

I have to display the values in the format dd/mm/YYYY HH:MM:SS AM/PM:

    11/09/2017  01:18:38 AM
    11/09/2017  01:34:30 AM
    11/09/2017  05:03:57 AM
    11/09/2017  09:55:48 AM
    11/09/2017  09:59:10 AM
    11/09/2017  12:09:05 PM
    11/09/2017  12:08:16 PM

I am using the following code to do that , however it doesnt change the format

data_f1['Reported Date'] = pd.to_datetime(data_f1['Reported Date'], 
   format="%m/%d/%Y %I:%M:%S %p")
like image 394
Jitendra Aswani Avatar asked Oct 25 '17 10:10

Jitendra Aswani


1 Answers

Given a string column, use pd.to_datetime to convert it to a datetime object column.

Given an already existing datetime column, use dt.strftime to convert it to a string column in a particular format.

This is how it works, and you can't change that.

df

                 date
0 2017-09-11 01:18:38
1 2017-09-11 01:34:30
2 2017-09-11 05:03:57
3 2017-09-11 09:55:48
4 2017-09-11 09:59:10
5 2017-09-11 12:09:05

df.date.dt.strftime("%m/%d/%Y %I:%M:%S %p")

0    09/11/2017 01:18:38 AM
1    09/11/2017 01:34:30 AM
2    09/11/2017 05:03:57 AM
3    09/11/2017 09:55:48 AM
4    09/11/2017 09:59:10 AM
5    09/11/2017 12:09:05 PM
Name: date, dtype: object

Note that there is no use in changing the representation of a datetime column, because those are datetime objects, and have their own representation defined by the __repr__ method of their class.

like image 81
cs95 Avatar answered Nov 03 '22 03:11

cs95