datetime.fromstr() - how?

Martin Bless m.bless at
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(
    "Represent and convert 'YYYY-MM-DD'-like date values."

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

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

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

More information about the Python-list mailing list