No strptime?

Manus Hand mjhand at concentric.net
Thu May 4 21:03:07 CEST 2000


I had the same problem, so I rolled my own (limited) strptime.

I import it like this:

# ----------------------------------------------------------
# Add a strptime() function to the time module, if necessary
# ----------------------------------------------------------
try: time.strptime
except:
    import strptime
    time.strptime = strptime.strptime

And here is the module that gets imported (written to Python 1.5.2):

import string

# ==========================================================================
# This function provides enough of the functionality of time.strptime()
# to make (my program) happy.  It is imported and used if the host platform
# does not support time.strptime().  This function is restricted as follows:
# (1) The only recognized arguments are %Y %m %d %b %H and %M
# (2) There must be a single character between each such argument in the
#  format string, and this character must match (exactly) the character
#  after the corresponding data from the string.  For example, you may
#  not use "%Y%m%d" as an argument for "19991125".  Instead you must
#  split the data up as "%Y-%m-%d" and "1999-11-25".  (Note that this
#  restriction [or something like it] is apparently in force in
#  "official" versions of time.strptime() as well.)
# ==========================================================================
def strptime(str, format):
    where, esc, result = 0, 0, [0] * 9
    spot, month = 'YmdHM', [None, 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
                                  'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
    try:
        for ch in '%s ' % format:
            if esc == 0:
                if ch == '%': esc = 1
                elif str[where] != ch: raise Oops
                else: where = where + 1
            elif esc == 1: escChar, esc = ch, 2
            elif esc == 2:
                data = string.split(str[where:], ch)[0]
                where, esc = where + len(data) + 1, 0
                if escChar == 'b': result[1] = month.index(string.upper(data))
                else: result[string.find(spot, escChar)] = int(data)
        # ---------------------------------------------------------
        # Validate ranges for month, day-of-month, hour, and minute
        # ---------------------------------------------------------
        if ((not (1 <= result[1] <= 12 and 1 <= result[2]
                 and  0 <= result[3] <= 23 and 0 <= result[4] <= 59))
        or (result[1] == 2 and result[2] > 28 + (result[0] % 4 == 0))
        or (result[2] > 30 + ((result[1] + (result[1] > 7)) % 2))): raise Oops
     except: raise ValueError
     return tuple(result)




More information about the Python-list mailing list