LoginSignup
451

More than 3 years have passed since last update.

Pythonで文字列 <-> 日付(date, datetime) の変換

Last updated at Posted at 2013-01-05

文字列から日付(datetime)

from datetime import datetime as dt

tstr = '2012-12-29 13:49:37'
tdatetime = dt.strptime(tstr, '%Y-%m-%d %H:%M:%S')

strptimeの第二引数は第一引数のフォーマットを渡す。
例えば、
tstr = '2012/12/29 13:49:37'だった場合、
dt.strptime(tstr, '%Y/%m/%d %H:%M:%S')

文字列から日付(date)

import datetime

tstr = '2012-12-29 13:49:37'
tdatetime = datetime.datetime.strptime(tstr, '%Y-%m-%d %H:%M:%S')
tdate = datetime.date(tdatetime.year, tdatetime.month, tdatetime.day)

日付から文字列

from datetime import datetime as dt

tdatetime = dt.now()
tstr = tdatetime.strftime('%Y/%m/%d')

参考
週など他の指定子(%Yみたいなやつ)が知りたい場合は、下記リンクの一番下から確認してください
基本的な日付型および時間型

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
451