临摹微笑
我对我能找到的所有不同方法进行了基准测试,结果如下:datetime.strftime - 1000000 次循环的时间:9.262935816994286转换为字符串- 1000000 次循环的时间:4.381643378001172datetime isoformat - 1000000 次循环的时间:4.331578577999608pendulum to_iso8601_string - 1000000 次循环的时间:18.471532950992696rfc3339 - 1000000 次循环的时间:24.731586036010412生成它的代码是:import timeitfrom datetime import datetimefrom pendulum import datetime as pendulum_datetimefrom rfc3339 import rfc3339dt = datetime(2011, 11, 4, 0, 5, 23, 283000)pendulum_dt = pendulum_datetime(2011, 11, 4, 0, 5, 23, 283000)repeats = 10**6print('datetime strftime')func1 = lambda: datetime.strftime(dt, "%Y-%m-%dT%H:%M:%S.%f%z")print(func1())print('Time for {0} loops: {1}'.format( repeats, timeit.timeit(func1, number=repeats)) )print('cast to string')func2 = lambda: str(dt)print(func2())print('Time for {0} loops: {1}'.format( repeats, timeit.timeit(func2, number=repeats)) )print('datetime isoformat')func3 = lambda: datetime.isoformat(dt)print(func3())print('Time for {0} loops: {1}'.format( repeats, timeit.timeit(func3, number=repeats)) )print('pendulum to_iso8601_string')func4 = lambda: pendulum_dt.to_iso8601_string()print(func4())print('Time for {0} loops: {1}'.format( repeats, timeit.timeit(func4, number=repeats)) )print('rfc3339')func5 = lambda: rfc3339(dt)print(func5())print('Time for {0} loops: {1}'.format( repeats, timeit.timeit(func5, number=repeats)) )