1

I have a DataFrame from Pandas:

import pandas as pd
inp = [{'date':'31/03/2021 11:50:12 PM', 'value':100}, 
{'date':'1/4/2021 0:53','value':110}, 
{'date':'2/04/2021 9:40:12 AM', 'value':200}]
df = pd.DataFrame(inp)
print(f'{df}\n')
print(df.dtypes)

output:

                       date  value
0  '31/03/2021 11:50:12 PM'    100
1           '1/4/2021 0:53'    110
2    '2/04/2021 9:40:12 AM'    100

date     object
value     int64
dtype: object

Now I want to convert the 'date' column from object to Datetime type so that the output will be as follow:

                 date  value
0 2021-03-31 23:50:12    100
1 2021-04-01 00:53:00    110
2 2021-04-02 09:40:12    100

date     datetime64[ns]
value             int64
dtype: object

I have tried to run this code:

df['date'] = pd.to_datetime(df['date'])
print(f'{df}\n')
print(df.dtypes)

But the output was as follow:

                 date  value
0 2021-03-31 23:50:12    100
1 2021-01-04 00:53:00    110
2 2021-02-04 09:40:12    100

date     datetime64[ns]
value             int64
dtype: object

As you can see, the panda to_datetime function mistook the first number in the column value with the dd/mm/yyyy hh:mm format as month. I would like to know how to convert the column to datetype format while also accounting for the different placement of the month and day numbers.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45

2 Answers2

0

Hi try it with this code.

df['date'] = pd.to_datetime(df['date'], format='%Y%m%d%H%M%S')
top talent
  • 615
  • 4
  • 17
0
def function_to_format(string):
       #Format date using datetime
       return formatted_datetime

dataframe['col']=dataframe['col'].apply(function_to_format)

Use datetime library to convert string to datetime, format the new dateime object using strftime() to convert to required format.

Waqar Ali
  • 86
  • 11