datetime.fromstr() - how?

Martin Bless m.bless at gmx.de
Tue Jul 20 15:16:17 CEST 2004


Below is what I'm currently using to construct datatime objects from
strings. Date and time objects are made up similar. To and from string
conversions are frequently needed in SQL neighborhood.

(1) Is there reason enough to ask for a 'datetime.fromstr(...)'
method? At least to convert ISO timestamps?

(2) You've got a better/different idea? Glad to see. Don't let me die
with this open question ... ;-)

mb - Martin


import datetime,time

class mysql_date(datetime.date):
    "Represent and convert 'YYYY-MM-DD'-like date values."

    def fromstr(Cls,s,f='%Y-%m-%d'):
        try:
            return Cls(*time.strptime(s,f)[:3])
        except:
            return None
    fromstr = classmethod(fromstr)

dt = mysql_date.fromstr('2004-07-20')
print repr(dt)
print dt

""" should print:
mysql_date(2004, 7, 20)
2004-07-20
"""




More information about the Python-list mailing list