为了账号安全,请及时绑定邮箱和手机立即绑定

ISO8601 转换器的最快日期时间

ISO8601 转换器的最快日期时间

慕桂英546537 2023-05-16 14:23:12
我正在寻找将 Python 日期时间对象呈现为 ISO8601 字符串的最快方法。有几种不同的方法可以做到这一点,本机datetime模块有strftime,isoformat并且只是平面旧的__str__。还有许多其他更奇特的方法,例如 Pendulum ( https://pendulum.eustace.io/ ),xml.utils.iso8601.tostring以及这里的其他一些方法https://wiki.python.org/moin/WorkingWithTime我希望有类似 ciso8601 的东西,它有一个很好的比较多种方法的基准: https: //github.com/closeio/ciso8601#benchmark
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

我对我能找到的所有不同方法进行了基准测试,结果如下:

  • datetime.strftime - 1000000 次循环的时间:9.262935816994286

  • 转换为字符串- 1000000 次循环的时间:4.381643378001172

  • datetime isoformat - 1000000 次循环的时间:4.331578577999608

  • pendulum to_iso8601_string - 1000000 次循环的时间:18.471532950992696

  • rfc3339 - 1000000 次循环的时间:24.731586036010412

生成它的代码是:

import timeit

from datetime import datetime

from pendulum import datetime as pendulum_datetime

from rfc3339 import rfc3339


dt = datetime(2011, 11, 4, 0, 5, 23, 283000)

pendulum_dt = pendulum_datetime(2011, 11, 4, 0, 5, 23, 283000)


repeats = 10**6


print('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))

    )


查看完整回答
反对 回复 2023-05-16
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信