Reputation: 1257
I am new to Pandas and Python. I want to convert Date Time Object to Date Time. I am having one column named requestDate which is for object type. Below is the one sample type
Tue, 04-Feb-2020 01:38 PM GMT+2
I am trying to convert above object into DateTime by adding following code, however its showing error unconverted data remains. I have removed GMT+2. Please help me in this.
test_df['requestDate'] = test_df['requestDate'].str.rstrip('GMT+2')
test_df['requestDate'] = pd.to_datetime(test_df['requestDate'], format='%a, %d-%b-%Y %H:%M %p')
Upvotes: 2
Views: 149
Reputation: 863501
There is problem last space in data, so added Series.str.strip
and then changed %H
to %I
for match hours in 12hour format:
test_df = pd.DataFrame({'requestDate':['Tue, 04-Feb-2020 01:38 PM GMT+2',
'Tue, 04-Feb-2020 01:38 PM GMT+2']})
test_df['requestDate'] = test_df['requestDate'].str.rstrip('GMT+2').str.strip()
test_df['requestDate'] = pd.to_datetime(test_df['requestDate'],
format='%a, %d-%b-%Y %I:%M %p')
print (test_df)
requestDate
0 2020-02-04 13:38:00
1 2020-02-04 13:38:00
Here add space cannot be used, because also M
is removed:
test_df['requestDate'] = test_df['requestDate'].str.rstrip(' GMT+2')
print (test_df)
requestDate
0 Tue, 04-Feb-2020 01:38 P
1 Tue, 04-Feb-2020 01:38 P
Possible solution with Series.str.replace
and escaped +
, because special regex character:
test_df['requestDate'] = test_df['requestDate'].str.replace(' GMT\+2', '')
print (test_df)
requestDate
0 Tue, 04-Feb-2020 01:38 PM
1 Tue, 04-Feb-2020 01:38 PM
Upvotes: 1