いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Pythonメモ-79 (ciso8601) (datetime, strptime, parse_datetime, 最速日付解析ライブラリ)

概要

ひょんなことで見つけたライブラリ。日付文字列をdatetimeに変換してくれるライブラリなのですが、最速みたいです。

www.peterbe.com

githubページは以下。

github.com

ciso8601という名前の通り、C言語で実装されています。

iso8601のフォーマットに対応しているので、その形式の文字列であればパース可能ということです。

とりあえず、一旦遊んでみました。

インストール

インストールは、condaでやりました。

(trypython) λ conda install ciso8601 -y
Solving environment: done

## Package Plan ##

  environment location: C:\Users\xxxx\Miniconda3\envs\trypython

  added / updated specs:
    - ciso8601


The following NEW packages will be INSTALLED:

    ciso8601:        1.0.8-py36_0     conda-forge

The following packages will be UPDATED:

    ca-certificates: 2018.1.18-0      conda-forge --> 2018.4.16-0      conda-forge
    certifi:         2018.1.18-py36_0 conda-forge --> 2018.4.16-py36_0 conda-forge

Preparing transaction: done
Verifying transaction: done
Executing transaction: done

とりあえず動かしてみる

以下のようなサンプルつくってちょっと動かしてみました。

python 最速日付解析ライブラリ ciso8601 のサンプル

結果

確かにめっちゃ速い。

通常の datetime.strptime の場合

$ python ./ciso8601_example.py --mode datetime
[datetime]      count: 100000   elapsed: 1.225secs

ciso8601

$ python ./ciso8601_example.py
[ciso8601]      count: 100000   elapsed: 0.022secs

備考

作者さんのgithubページのREADMEをよく見ると以下の記載を発見。

If time zone information is provided, an aware datetime object will be returned. Otherwise, the datetime is unaware. Please note that it takes more time to parse aware datetimes, especially if they're not in UTC. If you don't care about time zone information, use the parse_datetime_unaware method, which will discard any time zone information and is faster. Parsing aware date times requires the pytz module, otherwise time zone information is ignored and unaware datetimes are returned.

awareな日付の場合は、parse_datetimeを、naiveな日付の場合は、parse_datetime_unaware 使ったほうが速いよって書いてありますね。

上のサンプルはnaiveなので、parse_datetime_unaware を使ったほうが良かったかも。。


過去の記事については、以下のページからご参照下さい。

  • いろいろ備忘録日記まとめ

github.com

サンプルコードは、以下の場所で公開しています。

  • いろいろ備忘録日記サンプルソース置き場

github.com

github.com