I'm trying to code a program that will receive a date as an input which may or may not have milliseconds. Here's the code I'm using:
try:
start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S%z')
end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S%z')
except ValueError:
try:
start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S.%f%z')
end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError:
print("Cannot convert input dates")
exit()
The problem here is that instead of going to the except part when the date has milliseconds, the program raises an error and stops. Here's the error:
Exception has occurred: ValueError time data '2022-08-31 00:00:00.113439+00:00'
does not match format '%Y-%m-%d %H:%M:%S%z'
Why isn't the try/except handling it in the expected way? Is it a syntax issue?
EDIT: Replicable code
from datetime import date, timedelta, datetime, time
import argparse
def main(start_date, end_date):
try:
start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S%z')
end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S%z')
except ValueError:
try:
start_date = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S.%f%z')
end_date = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError:
print("Cannot convert input dates")
exit()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--start_date", required=True)
parser.add_argument("--end_date", required=True)
args = parser.parse_args()
main(args.start_date, args.end_date)
Configuration:
{ "version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Try Catch",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"args": [
"--start_date",
"2022-08-31 00:00:00.113439+00:00",
"--end_date",
"2022-09-03 00:00:00.113439+00:00"
]
}
]
}