Oct-27-2022, 08:53 PM
You could use datetime.
https://docs.python.org/3/library/dateti...e-behavior
https://docs.python.org/3/library/dateti...e-behavior
from datetime import datetime lines = ( "D4/7'2004\n", "D4/17'2004\n", "not a date\n", "D11/7'2005\n", "D11/17'2004\n", ) for line in lines: if line[0] == "D": line = line.strip()[1:] # Get rid of D and trailing whitespace date = datetime.strptime(line, "%m/%d'%Y") # Convert to DateTime line = "D"+date.strftime('%m/%d/%Y') # Convert back to string print(line)
Output:D04/07/2004
D04/17/2004
D11/07/2005
D11/17/2004
Or you could use re.split() and a string formatter. This example uses f"string style formatting.import re lines = ( "D4/7'2004\n", "D4/17'2004\n", "not a date\n", "D11/7'2005\n", "D11/17'2004\n", ) for line in lines: if line[0] == "D": line = line.strip()[1:] # Remove D and trailing whitespace d, m, y = re.split("/|'", line) # Split into month, day and year line = f"D{m:>02}/{d:>02}/{y}" # Pad month and day with leading 0 if needed print(line)
Output:D07/04/2004
D17/04/2004
D07/11/2005
D17/11/2004