2

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')

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.