Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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‘.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading