9
6

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のdatetime

Posted at

pythonのdatetimeについて何回も同じことを調べるため、備忘録としてまとめました。

※IDLE等の対話モードで検証しました。

必要なモジュール

import datetime
from pytz import timezone

取得

現在日時

TODAY = datetime.datetime.now()    #datetime.datetime.today() も同様の結果 
TODAY    #print(TODAY)
→ datetime.datetime(2019, 7, 19, 15, 55, 42, 566682)

単体要素

TODAY.year
→ 2019
TODAY.month
→ 7
TODAY.day
→ 19    
TODAY.hour
→ 15
TODAY.minute
→ 55
TODAY.second
→ 42
TODAY.microsecond
→ 566682

日付のみ

datetime.date.today()    #TODAY.date() も同様の結果
→ datetime.datetime(2019, 7, 19)

変更

時刻を「0時0分0秒」に変更したい

TODAY.replace(hour=0, minute=0, second=0, microsecond=0)
→ datetime.datetime(2019, 7, 19, 0, 0)

変換

日付型→文字列

TODAY.strftime("%Y年%m月%d日-%H時%M分%S秒")
→ '2019年07月19日-15時55分42秒'

文字列→日付型

DATE_STR = "2019-07-19T15:55:42Z"
datetime.datetime.strptime(DATE_STR, "%Y-%m-%dT%H:%M:%SZ")
→ datetime.datetime(2019, 7, 19, 15, 55, 42)

TimeZone

UTC

# UTCの現在時
datetime.datetime.utcnow()
→ datetime.datetime(2019, 7, 19, 7, 56, 45, 543211)

# 取得済みJSTをUTCへ変換
NOW = datetime.datetime.now()    # JST
NOW
→ datetime.datetime(2019, 7, 19, 7, 57, 02, 227882)
NOW.astimezone(timezone('UTC'))
→ datetime.datetime(2019, 7, 19, 7, 57, 02, 227882, tzinfo=<UTC>)

計算

# 今日の日時から昨日を計算
YESTERDAY = TODAY - datetime.timedelta(days=1)
YESTERDAY
→ datetime.datetime(2019, 7, 18, 15, 55, 42, 566682)

# 30分後の計算
TODAY + datetime.timedelta(minutes=30)
→ datetime.datetime(2019, 7, 19, 16, 25, 42, 566682)
# timedeltaの使える引数
[days, seconds, microseconds, milliseconds, minutes, hours, weeks]

比較

比較記号

 > >= < <= ==

TODAY > YESTERDAY
→ True
TODAY < YESTERDAY
→ False

aware VS naive

  • aware

    datetimeオブジェクトがTimeZone情報を持つオブジェクト

  • naive

    datetimeオブジェクトがTimeZone情報を持たないオブジェクト

→ aware同士、naive同士しか比較できない

以下はエラーとなる

AWARE_TIME = datetime.datetime.now().astimezone(timezone('Asia/Tokyo'))
AWARE_TIME
→ datetime.datetime(2019, 7, 19, 17, 57, 36, 45409, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)

NAIVE_TIME = datetime.datetime.now()
NAIVE_TIME
→ datetime.datetime(2019, 7, 19, 17, 57, 58, 622168)

# 比較
AWARE_TIME > NAIVE_TIME
----------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

解決法

#1 naiveに統一
AWARE_TIME.replace(tzinfo=None) > NAIVE_TIME
→ False    #エラーがなく、ちゃんと比較結果が表示されている
#2 awareに統一
AWARE_TIME > NAIVE_TIME.astimezone(timezone('Asia/Tokyo'))
→ False    #エラーがなく、ちゃんと比較結果が表示されている
9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?