timeには関数が多すぎる

timeライブラリには色々な関数があるが、関係がよくわからんので、図にまとめてみたが、分かりやすくなってなのは気にしないでくれ。


  • 「float」は1970年1月1日が開始してからの秒数。
  • 「tuple」は (年, 月, 日, 時, 分, 秒, 曜日, 年日, 夏時間フラグ) という構成のタプル*1
  • 「str (c-lang)」は "Tue Jan 02 03:04:05 2007" みたいな文字列。
  • 「∀str」は数字を埋め込んだ任意の文字列。

★がついていてる関数は、引数の時刻部分を省略することができる。その場合は「★の次にある関数の戻り値」を指定したことになる。

後ろにJSTとある関数は地方標準時の計算もしてくれる。ぶっちゃけ、[ ] の中の時間が足される。

strptime はちょっと説明が必要だ。この関数は strftime の逆を行う。文字列の中から数字を拾って時間を表すタプル(struct_time)にしてくれる。

>>> from time import *
>>> strptime('2007/01/02 03:04:05', '%Y/%m/%d %H:%M:%S')
(2007, 1, 2, 3, 4, 5, 1, 2, -1)
>>> strptime('Tue Jan 02 03:04:05 2007')  # この場合は第2引数を省略してもOK
(2007, 1, 2, 3, 4, 5, 1, 2, -1)


ちなみに、上の図はdot言語を使って書いた。ソースは以下のとおり。

digraph time {
  graph [compound = true, fontname ="VL PGothic", fontsize=13, rankdir = LR, nodesep = 2];
  edge [fontname = "VL Gothic", fontsize=13, fontcolor="navy"];
  node [fontname = "VL PGothic", fontsize=13];

  epoch [label = "float\n(Epoch UTC)"];
  tuple [label = "tuple\n(struct_time)"];
  astr [label = "∀str"];
  str [label = "str (c-lang)"];

  subgraph cluster1 {
    label = "str";
    fillcolor = "#ffffe0";
    style = filled;
    
    astr;
    str;
  }

  epoch -> tuple [label = "gmtime(★time)"];
  epoch -> tuple [label = "localtime(★time) JST[+9h]"];
  epoch -> str [label = "ctime(★time) JST[+9h]"];

  tuple -> str [label = "asctime(★localtime)"];
  tuple -> astr [label = "strftime(★localtime)"];  
  tuple -> epoch [label = "mktime() JST[-9h]"];
  
  str -> tuple [label = "strptime()", ltail = cluster1];
}

間違いがあった時の修正が楽なのでdot言語で書いたわけだが、正直面倒くさかった。pythonで図が書けるライブラリも色々とあるので、通常はそっちを使った方がいいだろう。

*1:gmtimeやlocaltimeの戻り値は実はstruct_timeで、色々属性を持っている。