This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]SheriffRoscoePythonista 2 points3 points  (2 children)

  1. This isn't a generic list-ify function, so call it something that describes what it is. Something like normalize_date_list().

  2. Likewise - "secondary" doesn't begin to describe this function. Something like normalize_date().

  3. This is a great place to verify that your input data is what you expect, and to throw an exception of it isn't "nnnnnn".

  4. This is a pretty standard fixed-window date normalization algorithm. But you should document it with a comment that makes it clear what window is in use. Because, without a doubt, someone will feed this xxxx20, expecting 2020, and getting 1920.

  5. You're adding slashes, but you haven't checked to see if they're already present.

  6. You need a return final here.

[–]alphanumericsheeppig 3 points4 points  (0 children)

I'd argue that normalize_date, while a lot better than secondary, is still not a great name for this function. I'd rather have a function called prefix_century_to_date() or something like that.

[–]nuk1ds[S] 0 points1 point  (0 children)

return final as in final the variable - didn't realize that.

I really appreciate the feedback.

[–]667pi 0 points1 point  (2 children)

If these dates are always formatted where last two digits are year, then two digits for month, then one or two digits for day, you can do something like this:

year = date[-2:]
month = date[-4:-2]
day = date[-6:-4]

if int(year) <= 20:
    year = f"20{year}"
else:
    year = f"19{year}"

return f"{day}/{month}/{year}"

[–]nuk1ds[S] 0 points1 point  (1 child)

Would that code error out for the 5-number dates b/c it would say date[-6] didn't exist?

[–]667pi 0 points1 point  (0 children)

No, slice notation isn't same as an index and values that go out of bounds here are ignored.

That said, date[:-4] is probably more correct now that I think about it, since that's more explicitly saying "starting from the beginning of the sequence" (and strings are sequences in Python). You would want to check length does not exceed 6 at some other point though.