LoginSignup
1
2

More than 5 years have passed since last update.

python > link > strftime()とstrptime()の振る舞い / コード

Last updated at Posted at 2016-10-05
対象環境
python 2.6.6 on CentOS 6.8

strftime()やstrptime()は過去にコーディングで使っていたが、記憶力が良くないので内容を忘れてしまう。

以下のリンクを見つけた。

大雑把にいうと、 d.strftime(fmt) は time モジュールの time.strftime(fmt, d.timetuple()) のように動作します。

「xのように動作します」と書かれて「x」を知らなければお手上げ。self-containedなドキュメントではない。

逆に datetime.strptime() クラスメソッドは日付や時刻に対応する書式文字列から datetime オブジェクトを生成します。

自分の理解では(間違っているかもしれない)

  • strftime() : datetime型を指定の書式文字列に変換
  • strptime() : 指定の書式文字列をdatetime型に変換

コードを実装してみた。
参考 http://qiita.com/shibainurou/items/0b0f8b0233c45fc163cd

import datetime

today = datetime.datetime.today()
print today

wrk = today.strftime("%Y-%m-%d_%H:%M:%S")
print "strftime:", wrk

dt = datetime.datetime.strptime(wrk, "%Y-%m-%d_%H:%M:%S")
print "strptime:", dt
結果
Success time: 0 memory: 9168 signal:0
2016-10-05 01:30:12.561105
strftime: 2016-10-05_01:30:12
strptime: 2016-10-05 01:30:12
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2