Python: Parsing Timestamps Embedded in Filenames
Question: I am working on a django project with avatar support and the system (which
isn't the greatest but needs to be maintained) requires that we embed a
timestamp of the form YYYYMMDDHHMM in the user generated avatar files and
concats that with the user_id, for example:

23_201308080930.png

I have written a function that parses these filenames and returns the most
recent timestamp:

    
    
    def _get_timestamp(self):
        """Return the timestamp of a user's most recently uploaded avatar."""
        path = settings.USER_AVATAR_DIRECTORY + self._get_dir()
        user_id = self.user_id
        file_re = re.escape(str(user_id)) + r"_\d{12}.png"
        times = []
        [times.append(file) for file in os.listdir(path) if re.match(file_re, file)]
        if times:
            digits = [re.findall("\d{12}", timestamp) for timestamp in times]
            timestamp = sorted(digits, reverse=True)[0][0]
            return timestamp
    

It works OK, but the double [0][0] pop necessary to traverse the list within a
list that is returned by the sequential regexen is a bit distasteful and
overall it all seems a bit blunt. Furthermore, although the avatars are in
reality spread over many directories (automatically generated by the user_id
but that's not really important here) I feel that possibly the brute force
regular expression searching could make a performance hit if a directory was
very large.

I am interested to know what might be the optimal and idiomatic solution for
this problem? Is it a candidate for generators or some form of lazy
evaluation?


Answer: I wouldn't use regexps for this; it's best to avoid them when you don't really
need them. Here's how I'd do it (untested):

    
    
    def _get_timestamp(self):
        """Return the timestamp of a user's most recently uploaded avatar."""
        path = settings.USER_AVATAR_DIRECTORY + self._get_dir()
        filenames = [filename for filename in os.listdir(path)
                     if filename.partition('_')[0] == str(self.user_id)]
        filenames.sort(reverse=True)
        return (filenames[0].rpartition('_')[2].partition('.')[0]
                if filenames else None)
    

