Various strings to dates.
wes weston
wweston at att.net
Sat Jan 24 12:09:21 EST 2004
#!/usr/local/bin/python -O
#NOTE: add missing MONTHS; DAYS not used
import datetime
import string
dateList = ["Fri, 23 Jan 2004 00:06:15",
"Thursday, 22 January 2004 03:15:06",
"Thursday, January 22, 2004, 03:15:06",
"2004, Thursday, 22 January 03:15:06"]
MONTHS = [("JANUARY",1),
("JAN",1),
("FEBRUARY",2),
("FEB",2),
#etc
]
DAYS = [("Monday",0),
("Mon",0),
#........
("Thursday",3),
("Thur",3)
]
#--------------------------------------------------------------------
def GetMonthInt(mstr):
#print "mstr=",mstr
for t in MONTHS:
if t[0].find(mstr) > -1:
return t[1]
return -1
#--------------------------------------------------------------------
class MyDateTime:
def __init__(self,oddstr):
tokens = oddstr.split()
temp = []
for t in tokens:
if t.find(":") > -1:
continue
if t[-1] == ',':
t = t[:-1]
temp.append(t)
tokens = temp
#for t in tokens:
# print t
year = -1
month = -1
day = -1
for t in tokens:
if t[0] in string.digits:
x = int(t)
if x > 31:
year = x
else:
day = x
continue
t = t.upper()
if t[0] in string.ascii_uppercase:
x = GetMonthInt(t)
if x <> -1:
month = x
continue
if year > -1 and month > -1 and day > -1:
self.Date = datetime.date(year,month,day)
else:
self.Date = None
def Show(self):
print self.Date.ctime()
#--------------------------------------------------------------------
if __name__ == '__main__':
for date in dateList:
dt = MyDateTime(date)
dt.Show()
More information about the Python-list
mailing list