[SciPy-user] Convert a date string to a date object

Bill Dandreta wjdandreta at att.net
Fri Aug 17 12:16:28 EDT 2007


Thanks for the demo. I added a 4th test for what I have used to speed
things up:

def str2date4(s):
    return datetime.date(int(s[:4]),int(s[5:7]),int(s[8:10]))

My results:

str2date1: 136.35 usec/pass

str2date2: 37.95 usec/pass

str2date3: 5.53 usec/pass

str2date4: 3.45 usec/pass

It is interesting to note that I ran the tests on a faster machine than
you did. My results for #1 were more than 3 X faster than yours but my
results for #3 were less than 10% faster!

Alexander Michael wrote:
> On 8/17/07, Bill Dandreta <wjdandreta at att.net> wrote:
>   
>> date=dt.date.fromtimestamp(time.mktime(time.strptime('2007-08-17',
>> "%Y-%m-%d")))
>>
>> Is very very slow!
>>
>> Is this the recommended Python way to convert a date string to a date
>> object?
>>
>> What is the fastest way to do this conversion?
>>     
>
> The time.mktime function is the primary culprit here, but is still
> faster to parse yourself if that works for you.
>
> import datetime
> import time
> import timeit
>
> def str2date1(s):
>     return datetime.date.fromtimestamp(time.mktime(time.strptime(s,
> '%Y-%m-%d')))
>
> def str2date2(s):
>     return datetime.date(*time.strptime(s, '%Y-%m-%d')[:3])
>
> def str2date3(s):
>     return datetime.date(*[int(s) for s in '2007-08-17'.split('-')])
>
> def test(f):
>     return '%s: %.2f usec/pass' % (f, 1000000 * timeit.Timer(f+"('2007-08-17')",
>         'from __main__ import ' + f).timeit(100)/100)
>
>   
>>>> print test('str2date1')
>>>>         
> str2date1: 451.57 usec/pass
>
>   
>>>> print test('str2date2')
>>>>         
> str2date2: 36.10 usec/pass
>
>   
>>>> print test('str2date3')
>>>>         
> str2date3: 6.06 usec/pass
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>
>   


-- 
Bill

wjdandreta at att.net

Gentoo Linux X86_64 2.6.20-gentoo-r8

Reclaim Your Inbox with http://www.mozilla.org/products/thunderbird/

All things cometh to he who waiteth as long as he who waiteth worketh like hell while he waiteth.




More information about the SciPy-User mailing list