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

Alexander Michael lxander.m@gmail....
Fri Aug 17 10:36:21 CDT 2007


On 8/17/07, Bill Dandreta <wjdandreta@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


More information about the SciPy-user mailing list