-1

Imn trying to write a function that will handle dates in a given format however, i'm having a few issues.

The first issue is when im applying this function using

df['AppointmentDate'] = df['AppointmentDate'].apply(func=date_handler)

The function works as intended while passing my own list, but it doesnt work when applying to DATAFRAME?

if __name__ == "__main__":
    date_handler(
        date_list=[
            '2022-07-18', '2022-07-02', '2022-07-25',  # YYYY-MM-DD

            '19-07-2022', '03-07-2022', '26-07-2022',  # DD-MM-YYYY

            '12-20-2023', '09-08-2022', '05-06-2023',  # MM-DD-YYYY

            '2022/08/17', '2023/10/20', '2023/01/01',  # YYYY/MM/DD

            '18/08/2022', '22/10/2023', '01/01/2023',  # DD/MM/YYYY

            '02/02/2023', '10/23/2023', '12/02/2023',  # MM/DD/YYYY

            '20230920', '20230822', '20230909',  # YYYYMMDD

            '20230920', '20230822', '20230909',  # DDMMYYYY

            '20230920', '20230822', '20230909',  # MMDDYYYY

my dataframe returns with empty values!

The second issue is when i am trying to add more try and excepts (to handle date time (YYYYMMDDHHMMSS+ TIMEZONE) i get the error: SyntaxError: too many statically nested blocks.

Here is my function.

@typechecked
def date_handler(date_list: any) -> print:
    for date in date_list:
        try:
            date_obj = datetime.datetime.strptime(date, '%Y-%m-%d')
        except ValueError:
            try:
                date_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
            except ValueError:
                try:
                    date_obj = datetime.datetime.strptime(date, '%m-%d-%Y')
                except ValueError:
                    try:
                        date_obj = datetime.datetime.strptime(date, '%Y/%m/%d')
                    except ValueError:
                        try:
                            date_obj = datetime.datetime.strptime(date, '%d/%m/%Y')
                        except ValueError:
                            try:
                                date_obj = datetime.datetime.strptime(date, '%m/%d/%Y')
                            except ValueError:
                                try:
                                    date_obj = datetime.datetime.strptime(date, '%Y%m%d')
                                except ValueError:
                                    try:
                                        date_obj = datetime.datetime.strptime(date, '%d%m%Y')
                                    except ValueError:
                                        try:
                                            date_obj = datetime.datetime.strptime(date, '%m%d%Y')
                                        except ValueError:
                                            print(f"Invalid date format: {date}")
                                            continue
                                        else:
                                            return None
                                    else:
                                        return date_obj.strftime('%Y-%m-%d')

Any reasons why this is?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mizanur Choudhury
  • 324
  • 2
  • 5
  • 16
  • Please ask one question at a time. See [ask]. And please make a [mre] for the Pandas issue; for specifics see [How to make good reproducible pandas examples](/q/20109391/4518341). – wjandrea Jul 24 '23 at 16:23

2 Answers2

0

Instead of creating several try-except wouldn't it be better to use the for-loop with continue? Example:

import datetime
def date_handler(date_list: any) -> print:
    formated_dates = []

    for date in date_list:
        for example in ['%Y-%m-%d', '%d-%m-%Y', '%m-%d-%Y']:
            try:
                date_obj = datetime.datetime.strptime(date, example)
                break
            except ValueError:
                continue
        formated_dates.append(date_obj)
    return formated_dates

formated_dates = date_handler(date_list=['2022-07-18', '2022-07-02', '2022-07-25'])
BoTop
  • 121
  • 6
  • this will continue iterating even if a correct conversion has been found – Sembei Norimaki Jul 24 '23 at 13:09
  • @SembeiNorimaki That's because it's just an example of how to reduce the lines of code and avoid repetition, in your code you would have a return or break that would end the loop! – BoTop Jul 24 '23 at 13:19
  • when i try this, python only converts the first date in my list? How would i iterate through the list of date formats? – Mizanur Choudhury Jul 25 '23 at 15:25
  • @MizanurChoudhury I edited my code to give an example of how you could do this, then you adapt to your needs! – BoTop Jul 26 '23 at 13:10
0

Put the different date formats in a list and iterate it.

If the try doesn't throw an exception break the loop, since a correct conversion has been found

The else after the loop captures the case where the loop hasn't broken, so all conversions have failed.

for date_format in ['%Y-%m-%d', '%d-%m-%Y', ...]:
  try:
    date_obj = datetime.datetime.strptime(date, date_format)
    break
  except ValueError:
    pass
else:
  # for hasn't broken, so no suitable date format was found
  print("Unable to convert date")
Sembei Norimaki
  • 745
  • 1
  • 4
  • 11