# -*- coding: utf-8 # This code is from the O'Reilly book "Python Standard Library" by # Fredrik Lundh. (ISBN: 0-596-00096-0) # # $Id$ __version__ = "$Revision$"[11:-2] import re import string MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] SPEC = { # map formatting code to a regular expression fragment "%a": "(?P[a-z]+)", "%A": "(?P[a-z]+)", "%b": "(?P[a-z]+)", "%B": "(?P[a-z]+)", "%C": "(?P\d\d?)", "%d": "(?P\d\d?)", "%D": "(?P\d\d?)/(?P\d\d?)/(?P\d\d)", "%e": "(?P\d\d?)", "%h": "(?P[a-z]+)", "%H": "(?P\d\d?)", "%I": "(?P\d\d?)", "%j": "(?P\d\d?\d?)", "%m": "(?P\d\d?)", "%M": "(?P\d\d?)", "%p": "(?Pam|pm)", "%R": "(?P\d\d?):(?P\d\d?)", "%S": "(?P\d\d?)", "%T": "(?P\d\d?):(?P\d\d?):(?P\d\d?)", "%U": "(?P\d\d)", "%w": "(?P\d)", "%W": "(?P\d\d)", "%y": "(?P\d\d)", "%Y": "(?P\d\d\d\d)", "%%": "%" } class TimeParser: def __init__(self, format): # convert strptime format string to regular expression 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, daytime): # match time string match = self.pattern.match(daytime) if not match: raise ValueError, "format mismatch" get = match.groupdict().get tm = [0] * 9 # extract date elements y = get("year") if y: y = int(y) if y < 68: y = 2000 + y elif y < 100: y = 1900 + y tm[0] = y m = get("month") if m: if m in MONTHS: m = MONTHS.index(m) + 1 tm[1] = int(m) d = get("day") if d: tm[2] = int(d) # extract time elements h = get("hour") if h: tm[3] = int(h) else: h = get("hour12") if h: h = int(h) if string.lower(get("ampm12", "")) == "pm": h = h + 12 tm[3] = h m = get("minute") if m: tm[4] = int(m) s = get("second") if s: tm[5] = int(s) # ignore weekday/yearday for now return tuple(tm) def strptime(string, format="%a %b %d %H:%M:%S %Y"): return TimeParser(format).match(string) if __name__ == "__main__": # try it out import time print strptime("2000-12-20 01:02:03", "%Y-%m-%d %H:%M:%S") print strptime(time.ctime(time.time())) ## (2000, 12, 20, 1, 2, 3, 0, 0, 0) ## (2000, 11, 15, 12, 30, 45, 0, 0, 0)