Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
376
Help us understand the problem. What is going on with this article?
@shibainurou

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

More than 1 year has passed since last update.

文字列から日付(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みたいなやつ)が知りたい場合は、下記リンクの一番下から確認してください
基本的な日付型および時間型

376
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
shibainurou
Qiita:Team使いたい

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
376
Help us understand the problem. What is going on with this article?