Where is time.strptime()?

Fredrik Lundh fredrik at effbot.org
Sat Nov 4 04:29:16 EST 2000


jschmitt at vmlabs.com wrote:
> I even looked for a 'time.py' in Python20\Lib and didn't find one.  Is
> it magic?

no, it's a C module.  see:

    http://www.python.org/doc/FAQ.html#4.70
    4.70. Where is the math.py (socket.py, regex.py, etc.) source file?

> strptime() -- parse string to time tuple according to format
> specification

always check the library reference for the full story:

    http://www.python.org/doc/current/lib/module-time.html
    "Note: This function relies entirely on the underlying platform's
    C library for the date parsing, and some of these libraries are
    buggy. There's nothing to be done about this short of a new,
    portable implementation of strptime().

    Availability: Most modern Unix systems.

in other words, if you cannot see it, it's because your platform
doesn't have it.

:::

here's a pure-Python partial implementation of strptime (reposted,
since I cannot find the original post in dejanews):

# time-example-6.py
# written by fredrik lundh, september 2000

import re
import string

MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
          "Sep", "Oct", "Nov", "Dec"]

SPEC = {
    "%a": "(?P<weekday>[a-z]+)",
    "%A": "(?P<weekday>[a-z]+)",
    "%b": "(?P<month>[a-z]+)",
    "%B": "(?P<month>[a-z]+)",
    "%C": "(?P<century>\d\d?)",
    "%d": "(?P<day>\d\d?)",
    "%D": "(?P<month>\d\d?)/(?P<day>\d\d?)/%y",
    "%e": "(?P<day>\d\d?)",
    "%h": "(?P<month>[a-z]+)",
    "%H": "(?P<hour>\d\d?)",
    "%I": "(?P<hour12>\d\d?)",
    "%j": "(?P<yearday>\d\d?\d?)",
    "%m": "(?P<month>\d\d?)",
    "%M": "(?P<minute>\d\d?)",
    "%p": "(?P<ampm12>am|pm)",
    "%R": "(?P<hour>\d\d?):(?P<minute>\d\d?)",
    "%S": "(?P<second>\d\d?)",
    "%T": "(?P<hour>\d\d?):(?P<minute>\d\d?):(?P<second>\d\d?)",
    "%U": "(?P<week>\d\d)",
    "%w": "(?P<weekday>\d)",
    "%W": "(?P<weekday>\d\d)",
    "%y": "(?P<year>\d\d)",
    "%Y": "(?P<year>\d\d\d\d)",
    "%%": "%"
}

class TimeParser:
    def __init__(self, format):
        format = string.join(re.split("(?:\s|%t|%n)+", format))
        pattern = []
        try:
            for spec in re.findall("%\w|%%|.", format):
                if spec[0] == "%":
                    spec = SPEC[spec]
                pattern.append(spec)
        except KeyError:
            raise ValueError, "unknown specificer: %s" % spec
        self.pattern = re.compile("(?i)" + string.join(pattern, ""))
    def match(self, string):
        match = self.pattern.match(string)
        if not match:
            raise ValueError, "format mismatch"
        group = match.group
        tm = [0] * 9
        y, m, d = group("year", "month", "day")
        if y:
            y = int(y)
            if y < 68:
                y = 2000 + y
            elif y < 100:
                y = 1900 + y
            tm[0] = y
        if m:
            if m in MONTHS:
                m = MONTHS.index(m) + 1
            tm[1] = int(m)
        if d: tm[2] = int(d)
        h, m, s = group("hour", "minute", "second")
        if h:
            tm[3] = int(h)
        else:
            h = group("hour12")
            if h:
                h = int(h)
                if string.lower(group("ampm")) == "pm":
                    h = h + 12
            tm[3] = int(h)
        if m: tm[4] = int(m)
        if s: tm[5] = int(s)
        # ignore weekday/yearday for now
        return tm

def strptime(string, format="%a %b %d %H:%M:%S %Y"):
    return TimeParser(format).match(string)

:::

>>> print strptime("2000-12-20 01:02:03", "%Y-%m-%d %H:%M:%S")
[2000, 12, 20, 1, 2, 3, 0, 0, 0]
>>> print strptime(time.ctime(time.time()))
[2000, 9, 12, 10, 31, 43, 0, 0, 0]

:::

also, if you're going to convert lots of dates, creating a TimeParser
instance is more efficient than calling strptime over and over again.

</F>





More information about the Python-list mailing list