Safe saving and loading of files?

I’m writing 2 classes, one saves, one loads. :face_with_spiral_eyes:

The separation is due to the processes being independent (saving / loading of machine learning models.)

To make sure there isn’t any overwrite, I use Path.makedir that fails on existent directories, and always creates a timestamped directory (as said, if it’s not already there.)

The format I like for timestamp looks like this: 2024_12_08_T15_17_16Z. It’s reasonably unique in my circumstances, and also readable.

Now, when loading a model, the user can pass the parent folder and optionally the timestamped one (for obvious reasons, it’s hard to type.)

I haven’t found any similar format that can directly be parsed by datetime and return a boolean “date or not date”. Even the datetime.fromisoformat(...) only accepts date, not time.

I currently use a regex:

def is_date_format(dirname: Path) -> bool:
  """Make sure the directory is the format we chose for saving."""
  regex = r"\d{4}_(:?\d{2}_){2}T(:?\d{2}_){2}\d{2}Z$"
  return bool(re.match(regex, dirname.name))

that I use both in saving and loading, ensuring that at some point the saving format was not changed.

So, if at some point the saving format changes to 12_08_T15_17_16Z the regex will fail.

Does this approach look reliable to you, or you’d recommend something else?

1 Like

I believe that datetime.strptime and datetime.strftime with a global constant containing the expected format should cover your needs. See here for a list of supported codes.

2 Likes

That’s amazing! I missed strptime method. Thanks