How to convert date as 'Monday 1st' to'Monday 1' in python?


I have tried a lot. Banning words doesn’t help, removing certain characters doesn’t help.

The datetime module doesn’t have a directive for this. It has things like %d which will give you today’s day, for example 24.

I have a date in the format of ‘Tuesday 24th January‘ but I need it to be ‘Tuesday 24 January‘.

Is there a way to remove st,nd,rd,th. Or is there an even better way?

EDIT: even removing rd would remove it from Saturday. So that doesn’t work either.

>Solution :

You can use a regex:

import re

d = 'Tuesday 24th January'
d = re.sub(r'(\d+)(st|nd|rd|th)', r'\1', d)  # \1 to restore the captured day

# Output
Tuesday 24 January

For Saturday 21st January:

d = 'Saturday 21st January'
d = re.sub(r'(\d+)(st|nd|rd|th)', r'\1', d)

# Output
Saturday 21 January

Leave a Reply Cancel reply