Jazzin
Jazzin

Reputation: 55

Parsing Dates In Python

I have a list of dates from input like the ones below.

I am working on a project and only want to accept the dates that follow the format April 1, 1990 or the January 13, 2003 (taking in any month) format from user input, and any other date format I do not want to accept. I am struggling on how I would use the replace or find function to obtain these goals? Once I receive that format I want to print out the date in this format 7/19/22. If I have the dates in the right format I used the replace function to replace the space, and comma but how would I take that month and replace it with its numerical value? Sorry for all these questions I am just stuck and have been working on this for a while now.

April 1, 1990
November 2 1995
7/19/22
January 13, 2003

userinput = input("Please enter date")

parsed_date = userinput.replace(" ", "/", 2)
new_parsed_date = parsed_date.replace(',',"")
print(new_parsed_date)

March/1/2019
Here is my output when I parse the date. Is there also any easier way to do this task?

Upvotes: 1

Views: 7643

Answers (2)

Hsins
Hsins

Reputation: 43

I can't really understand what you're going to do. You said that you only want to accept the certain dates formats from user input and ignore other dates formats.

April 1, 1990      # Accept
January 13, 2003   # Accept
November 2 1995    # Ignore (lack of comma)
7/19/22            # Ignore (use numerical value in month field)

May I just think that you would like to accept the format like January 13, 2003 and print or save them in the format 01/13/2003?

Then you should consider strptime() and strftime() methods for datetime object.

# get the date string from user input
date_input = input("Please Enter Date: ") 
input_format = "%B %d, %Y"
output_format = "%m/%d/%Y"

try:
    parsered_date = datetime.datetime.strptime(date_input, input_format)
                                     .strftime(output_format)
    print(parsered_date)
except ValueError:
    print("This is the incorrect date string format.")

Upvotes: 1

Michael Anckaert
Michael Anckaert

Reputation: 953

You should take a look at the strptime method of the Python datetime object.

Basically you would write code that looks like this:

>>> from datetime import datetime
>>> datetime.strptime("January 13, 2003", "%B %d, %Y")
datetime.datetime(2003, 1, 13, 0, 0)

Documentation for strptime: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

Upvotes: 1

Related Questions