0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで日付操作

Last updated at Posted at 2019-06-15

ライブラリのインポート

from datetime import datetime
import dateutil.parser

現在時刻取得(datetime型で)

dt = datetime.now()

任意時刻をdatetime型で

dt = datetime(2019,6,16,12,34,56) #年,月,日,時,分,秒

文字列 ⇒ datetime型へ

フォーマットにあっていないとエラーになる

tstr='2019-06-16 12:34:56' 
dt = datetime.strptime(tstr, '%Y-%m-%d %H:%M:%S')

文字列 ⇒ dateutil.parser.parseを利用してdatetime型へ

strptimeより柔軟だが、strptimeより遅い。(6倍弱)

tstr='2019/6/16 12:34' 
dt = dateutil.parser.parse(tstr)

datetime型 ⇒ unixtimestamp型へ

ts = dt.timestamp()

unixtimestamp ⇒ datetime型へ

dt = datetime.fromtimestamp(ts)

datetime型 ⇒ 日付文字列(書式指定)

tstr1 = dt.strftime('%Y-%m-%d %H:%M:%S') # 2019-06-16 12:34:56
tstr2 = dt.strftime('%Y%m%d_%H%M')       # 20190616_1234
tstr3 = dt.strftime('%Y-%m-%d')          # 2016-06-16  日付だけ
tstr4 = dt.strftime('%H:%M')             # 12:34       時刻だけ
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?