0

I have a list of multiple formats of dates (strings), and I would like to sort format them all to be the same, and sort them by date, I have worked out a complicated way of making this work. but I am trying to clean up my code a bit, and Im under the assumption that there is a much simpler way of doing it.

Nov 4, 2020

Nov 23, 2020

2020-11-12 yyyy-mm-dd

2020-11-10

11/02/2020 mm/dd/yyyy

11/18/2020

THANKS!

2
  • in a date like 11/02/2020, is it month or day first? any specific language? Commented Nov 25, 2020 at 15:51
  • month, day, year. python. ill edit the post. thank you. Commented Nov 25, 2020 at 16:02

1 Answer 1

1

if the formats are as "standard" as this, you can make use of dateutil's parser:

from dateutil import parser

l = ["Nov 4, 2020", "Nov 23, 2020", "2020-11-12", "2020-11-10", "11/02/2020", "11/18/2020"]

dates = sorted(map(parser.parse, l))
# [datetime.datetime(2020, 11, 2, 0, 0),
#  datetime.datetime(2020, 11, 4, 0, 0),
#  datetime.datetime(2020, 11, 10, 0, 0),
# ...]

# to common format: e.g.
dates_formatted = [d.strftime('%Y-%m-%d') for d in dates] # == d.date().isoformat()
# ['2020-11-02',
#  '2020-11-04',
#  '2020-11-10',
#  ...]
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.