1

I'm trying to convert the existing dates from March 02, 2019 6:30 - 11:00 pm to 3/2/19 format but I can't get any idea as to how I can do it.

These are the dates:

datelist = [
    "March 02, 2019 6:30 - 11:00 pm",
    "June 21, 2019",
    "March 22, 2019 5:00 - 10:00 pm",
    "May 01, 2019 - June 15, 2019 11:59 pm",
    "May 02, 2019 5:30 - 8:00 pm",
    "May 04, 2019 5:00 - 10:30 pm",
    "September 08, 2018 6:00 - 10:00 pm",
]

for date in datelist:
    print(date)

Expected output:

3/2/2019
6/21/2019
3/22/2019
5/1/2019 - 6/15/2019
5/2/2019
5/4/2019
9/8/2018

This is the closest that I could find out:

import datetime

date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime(date_time_str, '%b %d %Y %I:%M%p').strftime('%m/%d/%Y')
print(date_time_obj)

But, that doesn't actually serve the purpose when I have different type of dates in the list.

How can I convert dates to the desired format?

robots.txt
  • 96
  • 2
  • 10
  • 36
  • 1
    Possible duplicate of [How to convert a date string to different format](https://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format) – Jake P Aug 13 '19 at 19:18
  • 1
    Wrong link @Jake P. It's actually the opposite and also the strings there are uniform whereas the list I pasted above are haphazard. – robots.txt Aug 13 '19 at 19:32

4 Answers4

3

I like using the module dateutil because it internally tries to make an educated guess of the incoming date format:

from dateutil import parser as dateparser

date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = dateparser.parse(date_time_str)
print(date_time_obj.strftime('%m/%d/%Y'))

It seems to be pretty robust.

Sergio Pulgarin
  • 869
  • 8
  • 20
2

You can also use regex to find the dates and then convert to date time using datetime and strftime to represent in your desired format:

import re
import datetime
datelist = [
    "March 02, 2019 6:30 - 11:00 pm",
    "June 21, 2019",
    "March 22, 2019 5:00 - 10:00 pm",
    "May 01, 2019 - June 15, 2019 11:59 pm",
    "May 02, 2019 5:30 - 8:00 pm",
    "May 04, 2019 5:00 - 10:30 pm",
    "September 08, 2018 6:00 - 10:00 pm",
]
find_dates = re.compile(r'((?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{2},\s\d{4})')
new_dates = [re.findall(find_dates, x) for x in datelist]
datetime_dates = []
for x in new_dates:
    dts = []
    for y in x:
        dt = datetime.datetime.strptime(y, '%B %d, %Y')
        dts.append(dt.strftime("%m/%d/%Y"))
    datetime_dates.append('-'.join(dts))

print(datetime_dates)

output:

['03/02/2019', 
 '06/21/2019', 
 '03/22/2019', 
 '05/01/2019-06/15/2019', 
 '05/02/2019', 
 '05/04/2019', 
 '09/08/2018']
Anna Nevison
  • 2,709
  • 6
  • 21
0

use my_date = datetime.strptime("June 21, 2019","%B %d, %Y") to convert from input format to datetime. next print in required format: my_date.strftime("%m/%d/%Y")

On input: "June 21, 2019", resulted: '06/21/2019'

This site has comprehensive guide: https://stackabuse.com/how-to-format-dates-in-python/

Guy Tabak
  • 128
  • 7
  • 2
    see @Sergio Pulgarin comment, it's more robust. Make sure you understand how to use the formatting of datetime module. – Guy Tabak Aug 13 '19 at 19:34
0

The following code gives you exactly the same output you are looking for, handling the case where you have more than one date by line:

datelist = [
    "March 02, 2019 6:30 - 11:00 pm",
    "June 21, 2019",
    "March 22, 2019 5:00 - 10:00 pm",
    "May 01, 2019 - June 15, 2019 11:59 pm",
    "May 02, 2019 5:30 - 8:00 pm",
    "May 04, 2019 5:00 - 10:30 pm",
    "September 08, 2018 6:00 - 10:00 pm",
]


import datetime


def parse(x):
    p = ""
    for format_ in ['%B %d, %Y %H:%M', '%B %d, %Y', '%B %d, %Y %H:%M %p']:
        try:
            p = datetime.datetime.strptime(x.strip(), format_)
        except ValueError:
            continue
    return p


def format_(x): 
    if type(x) == str:
        return x
    return x.strftime("%-m/%-d/%Y")    

final_dates = []


for dates in datelist:
    final_string = []
    for date in dates.split(" - "):
        date = parse(date)
        date = format_(date)
        if len(date):
            final_string.append(date)
    final_dates.append("-".join(final_string))

Out[218]: 
['3/2/2019',
 '6/21/2019',
 '3/22/2019',
 '5/1/2019 - 6/15/2019',
 '5/2/2019',
 '5/4/2019',
 '9/8/2018']
ivallesp
  • 2,018
  • 1
  • 14
  • 21