On some platforms, the time module contains a strptime
function, which is pretty much the opposite of strftime. Given a
string and a pattern, it returns the corresponding time tuple:
Example: Using the time.strptime function to parse dates and times
# File: `time-example-6.py <time-example-6.py>`__
import time
# make sure we have a strptime function!
try:
strptime = time.strptime
except AttributeError:
from strptime import strptime
print strptime("31 Nov 00", "%d %b %y")
print strptime("1 Jan 70 1:30pm", "%d %b %y %I:%M%p")
The time.strptime function is currently only made available by
Python if it’s provided by the platform’s C libraries. For
platforms that don’t have a standard implementation (this includes
Windows), here’s a partial replacement:
Example: A strptime implementation
# File: `strptime.py <strptime.py>`__
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)