fromisoformat()
从Python 3.7开始,
datetime该类具有
fromisoformat方法。应当指出,这也可以应用于以下问题:性能与
strptime()
strptime,但是 使用内置 方法 可以使
性能提高90倍
fromisoformat!
%timeit isofmt(datelist)569 µs ± 8.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)%timeit slice2int(datelist)5.51 ms ± 48.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)%timeit normalstrptime(datelist)52.1 ms ± 1.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)from datetime import datetime, timedeltabase, n = datetime(2000, 1, 1, 1, 2, 3, 420001), 10000datelist = [(base + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(n)]def isofmt(l): return list(map(datetime.fromisoformat, l))def slice2int(l): def slicer(t): return datetime(int(t[:4]), int(t[5:7]), int(t[8:10])) return list(map(slicer, l))def normalstrptime(l): return [datetime.strptime(t, '%Y-%m-%d') for t in l]print(isofmt(datelist[0:1]))print(slice2int(datelist[0:1]))print(normalstrptime(datelist[0:1]))# [datetime.datetime(2000, 1, 1, 0, 0)]# [datetime.datetime(2000, 1, 1, 0, 0)]# [datetime.datetime(2000, 1, 1, 0, 0)]
Python 3.8.3rc1 x64 / Win10
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)