datetime.fromstr() - how?

Jeff Sandys sandysj at juno.com
Tue Jul 20 12:28:19 EDT 2004


Martin Bless wrote:
> 
> 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?
Does this help?
http://www.python.org/cgi-bin/moinmoin/WorkingWithTime

> 
> (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