i’ve combined many dateframes but the date is not match as it’s look like (datetime & int) as below , it’s contains float number and datetime date.
JavaScript
x
13
13
1
Date
2
2022-05-31 00:00:00
3
2022-05-31 00:00:00
4
2022-05-31 00:00:00
5
2022-05-31 00:00:00
6
44713.0
7
44713.0
8
44713.0
9
44713.0
10
44713.0
11
44713.0
12
44713.0
13
i’m tried to use the below codes but i found error messages (ValueError: mixed datetimes and integers in passed array) or i found this error elso(‘<‘ not supported between instances of ‘Timestamp’ and ‘int’)
So how can i change the date formatting to be all like dd-mm-yyyy
The full code:-
JavaScript
1
15
15
1
import pandas as pd
2
import datetime as dt
3
import xlrd
4
from datetime import datetime
5
6
7
IN_df=pd.concat([IN_df1, IN_df2,IN_df3,IN_df4,IN_df5,IN_df6,IN_df7,IN_df8]).fillna("")
8
IN_df=IN_df[(IN_df['Status']=='No Show')&(IN_df['Site']== 'Cairo')]
9
IN_df=IN_df.filter(items=['Date','SF ID','Name','Direct Manager','Department','Shift','Status','Reporting Feedback']).reset_index(drop=True).convert_dtypes()
10
11
IN_df['Date']=IN_df['Date'].apply(xlrd.xldate_as_datetime, args=(0,))
12
IN_df['Date']=pd.to_datetime(IN_df['Date']).dt.date
13
14
IN_df.tail()
15
Advertisement
Answer
Check Below code:
JavaScript
1
9
1
import pandas as pd
2
3
4
df = pd.DataFrame({'date':['2022-05-31 00:00:00','2022-05-31 00:00:00','44713','2022-05-31 00:00:00','44713']})
5
6
df['new_date'] = df.apply(lambda x: pd.to_datetime(int(x.date), unit='D', origin='1899-12-30') if x.date.isdigit() else pd.to_datetime(x.date) , axis=1)
7
8
df
9
Output:
Updating code as per OP comment below:
JavaScript
1
6
1
df = pd.DataFrame({'date':['2022-05-31 00:00:00','2022-05-31 00:00:00','44743.0','2022-05-31 00:00:00','44713']})
2
3
df['new_date'] = df.apply(lambda x: pd.to_datetime(float(x.date), unit='D', origin='1899-12-30') if x.date[:-2].isdigit() else pd.to_datetime(x.date) , axis=1)
4
5
df
6
Output: