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

Time:01-24

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.

CodePudding user response:

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
print(d)

# Output
Tuesday 24 January

For Saturday 21st January:

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

# Output
Saturday 21 January

CodePudding user response:

You can use Python's built-in strftime method to format the date and remove the 'st', 'nd', 'rd', 'th' from the day.

Here is an example:

import re

date_string = 'Tuesday 24th January'
date_string = re.sub(r'(?i)(st|nd|rd|th)', '', date_string)
print(date_string) # output: Tuesday 24 January

  • Related