0

I have couple of date string with following pattern MM DD(st, nd, rd, th) YYYY HH:MM am. what is the most pythonic way for me to replace (st, nd, rd, th) as empty string ''?

s = ['st', 'nd', 'rd', 'th']
string = 'Mar 1st 2017 00:00 am'
string = 'Mar 2nd 2017 00:00 am'
string = 'Mar 3rd 2017 00:00 am'
string = 'Mar 4th 2017 00:00 am'
for i in s:
    a = string.replace(i, '')
a = [string.replace(i, '') for i in s][0]
print(a)

2 Answers 2

3

The most pythonic way is to use dateutil.

from dateutil.parser import parse
import datetime

t = parse("Mar 2nd 2017 00:00 am")

# you can access the month, hour, minute, etc:
t.hour # 0
t.minute # 0
t.month # 3

And then, you can use t.strftime(), where the formatting of the resulting string is any of these: http://strftime.org/

If you want a more appropriate representation of the time(like for example in your proper locale), then you could do t.strftime("%c"), or you could easily format it to the answer you wanted above.

This is much safer than a regex match because dateutil is a part of the standard library, and returns to you a concise datetime object.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use a regular expression as follows:

import re        

strings = ['Mar 1st 2017 00:00 am', 'Mar 2nd 2017 00:00 am', 'Mar 3rd 2017 00:00 am', 'Mar 4th 2017 00:00 am']

for string in strings:
    print(re.sub('(.*? \d+)(.*?)( .*)', r'\1\3', string))

This would give you:

Mar 1 2017 00:00 am
Mar 2 2017 00:00 am
Mar 3 2017 00:00 am
Mar 4 2017 00:00 am

If you want to restrict it do just st nd rd th:

print(re.sub('(.*? \d+)(st|nd|rd|th)( .*)', r'\1\3', string))

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.