datetime.fromstr() - how?

Martin Bless m.bless at gmx.de
Thu Jul 22 10:43:41 CEST 2004


Dan Bishop <> wrote in
<ad052e5c.0407201114.71ba95a0 at posting.google.com>:

>
>import datetime
>def strToDate(ymd):
>   return datetime.date(*map(int, ymd.split('-')))

Yes, thanks, I like your solution better. This way I don't have to use
'time' as a second module. For those interested, here's what I'm using
now.

It's a pity the 'datetime' module lacks 'time.strptime()'
functionality. In contrast it does provide 'strftime()' methods.

mb - Martin


# date,time,datetime,timestamp handling for MySQLdb
# independant from mxdate

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

    def fromstr(Cls,s):
        try:
            return Cls(*map(int,s.split('-'))[:3])
        except:
            return None
    fromstr = classmethod(fromstr)

class mysql_time(datetime.time):
    "Represent and convert 'HH:MM:SS'-like time values."

    def fromstr(Cls,s):
        "Construct instance from string."
        try:
            return Cls(*map(int,s.split(':'))[:3])
        except:
            return None
    fromstr = classmethod(fromstr)

class mysql_datetime(datetime.datetime):
    "Represent and convert 'YYYY-MM-DD HH:MM:SS'-like datetime
values."

    def fromstr(Cls,s):
        "Initialize instance from string."
        try:
            return Cls(*map(int,s.replace('-',' ').replace(':','
').split())[:6])
        except:
            return None
    fromstr = classmethod(fromstr)

class mysql_timestamp(datetime.datetime):
    "Represent and convert 'YYYYMMDDHHMMSS'-like timestamp values."

    def fromstr(Cls,s,f='%Y%m%d%H%M%S'):
        "Initialize instance from string."
        try:
            return
Cls(*map(int,[s[0:4],s[4:6],s[6:8],s[8:10],s[10:12],s[12:14]]))
        except:
            return None
    fromstr = classmethod(fromstr)

    def __str__(self):
        return self.strftime('%Y%m%d%H%M%S')

myconv = MySQLdb.converters.conversions.copy()
myconv.update({
    FIELD_TYPE.TIMESTAMP : mysql_timestamp.fromstr,
    FIELD_TYPE.DATETIME : mysql_datetime.fromstr,
    FIELD_TYPE.DATE : mysql_date.fromstr,
    FIELD_TYPE.TIME : mysql_time.fromstr,
    })




More information about the Python-list mailing list