工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python datetimeマスター:日付・時刻・タイムゾーン実践ガイド

Python datetimeマスター

ハンズオン例と明確な解説で、Pythonでの日付・時刻操作を習得します。

動画:Python datetime – 日付と時刻を扱う

Pythonのdatetimeモジュールは、日付と時刻操作の強力なツールを提供します。現在時刻取得からフォーマット、タイムゾーン処理まで、一般的なタスクを歩いていきます。


例1:現在の日時を取得

import datetime datetime_object = datetime.datetime.now() print(datetime_object) 

出力例:

2018-12-19 09:26:03.478039

import datetimeでモジュールをインポート。datetimeクラスのnow()メソッドがローカル日時を返します。


例2:現在の日付を取得

import datetime date_object = datetime.date.today() print(date_object) 

出力:

2018-12-19

dateクラスのtoday()で現在のカレンダー日付を取得。


datetimeモジュールを探索

dir(datetime)で全属性とクラスを列挙:

import datetime print(dir(datetime)) 

出力:

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

主要クラス:date、time、datetime、timedelta。


datetime.date クラス

dateクラスはカレンダー日付(年、月、日)を表現。


例3:日付オブジェクト作成

import datetime d = datetime.date(2019, 4, 13) print(d) 

結果:

2019-04-13

date()コンストラクタはyear、month、dayを引数に取ります。変数aはdateインスタンス。


dateクラスのみインポート:

from datetime import date a = date(2019, 4, 13) print(a)

例4:現在日付

クラスメソッドtoday()使用:

from datetime import date today = date.today() print("Current date =", today)

例5:タイムスタンプから変換

Unixタイムスタンプは1970-01-01 UTCからの秒数。fromtimestamp()で変換:

from datetime import date timestamp = date.fromtimestamp(1326244364) print("Date =", timestamp)

出力:

Date = 2012-01-11

例6:年・月・日へのアクセス

from datetime import date today = date.today() print("Current year:", today.year) print("Current month:", today.month) print("Current day:", today.day)

datetime.time

timeクラスは日付なしの時刻を格納。


例7:時刻オブジェクト作成

from datetime import time a = time() print("a =", a) b = time(11, 34, 56) print("b =", b) c = time(hour=11, minute=34, second=56) print("c =", c) d = time(11, 34, 56, 234566) print("d =", d)

結果:

a = 00:00:00 b = 11:34:56 c = 11:34:56 d = 11:34:56.234566

例8:時刻構成要素の検査

from datetime import time a = time(11, 34, 56) print("hour =", a.hour) print("minute =", a.minute) print("second =", a.second) print("microsecond =", a.microsecond)

出力:

hour = 11 minute = 34 second = 56 microsecond = 0

datetime.datetime

datetimeクラスは日付と時刻の両情報を結合。


例9:datetimeオブジェクト作成

from datetime import datetime # year, month, day A = datetime(2018, 11, 28) print(A) # 完全指定 B = datetime(2017, 11, 28, 23, 55, 59, 342380) print(B)

結果:

2018-11-28 00:00:00 2017-11-28 23:55:59.342380

年月日は必須、時分秒マイクロ秒はデフォルト0。


例10:構成要素検査 & タイムスタンプ

from datetime import datetime A = datetime(2017, 11, 28, 23, 55, 59, 342380) print("year =", A.year) print("month =", A.month) print("day =", A.day) print("hour =", A.hour) print("minute =", A.minute) print("timestamp =", A.timestamp())

出力:

year = 2017 month = 11 day = 28 hour = 23 minute = 55 timestamp = 1511913359.34238

datetime.timedelta

timedeltaオブジェクトは2つの日時間の期間を表現。


例11:日付・時刻の差分

from datetime import datetime, date T1 = date(year=2018, month=7, day=12) T2 = date(year=2017, month=12, day=23) T3 = T1 - T2 print("T3 =", T3) T4 = datetime(year=2018, month=7, day=12, hour=7, minute=9, second=33) T5 = datetime(year=2019, month=6, day=10, hour=5, minute=55, second=13) T6 = T4 - T5 print("T6 =", T6) print("type of T3 =", type(T3)) print("type of T6 =", type(T6))

出力:

T3 = 201 days, 0:00:00 T6 = -333 days, 1:14:20 type of T3 = <class 'datetime.timedelta'> type of T6 = <class 'datetime.timedelta'>

例12:timedeltaオブジェクト同士の減算

from datetime import timedelta T1 = timedelta(weeks=2, days=5, hours=1, seconds=33) T2 = timedelta(days=4, hours=11, minutes=4, seconds=54) T3 = T1 - T2 print("T3 =", T3)

出力:

T3 = 14 days, 13:55:39

例13:負のtimedelta

from datetime import timedelta T1 = timedelta(seconds=33) T2 = timedelta(seconds=54) T3 = T1 - T2 print("T3 =", T3) print("abs(T3) =", abs(T3))

出力:

T3 = -1 day, 23:59:39 abs(T3) = 0:00:21

例14:timedeltaの総秒数

from datetime import timedelta T = timedelta(days=5, hours=1, seconds=33, microseconds=233423) print("total seconds =", T.total_seconds())

出力:

total seconds = 435633.233423

日付加算、timedeltaの数値乗算、float除算での期間スケーリングも可能。


日付のフォーマットとパース

ロケールにより日付形式は様々(米国mm/dd/yyyy、英国dd/mm/yyyy等)。Pythonのstrftime()とstrptime()でdatetimeオブジェクトとフォーマット文字列を相互変換。


Python strftime() – datetimeを文字列へ

from datetime import datetime now = datetime.now() # 時:分:秒 T = now.strftime("%H:%M:%S") print("time:", T) # 米国形式 S1 = now.strftime("%m/%d/%Y, %H:%M:%S") print("S1:", S1) # 英国形式 S2 = now.strftime("%d/%m/%Y, %H:%M:%S") print("S2:", S2)

典型的出力:

time: 04:34:52 S1: 12/26/2018, 04:34:52 S2: 26/12/2018, 04:34:52

主要フォーマットコード:%Y年、%m月、%d日、%H時、%M分、%S秒。


Python strptime() – 文字列をdatetimeへ

from datetime import datetime date_string = "21 June, 2018" print("date_string =", date_string) date_object = datetime.strptime(date_string, "%d %B, %Y") print("date_object =", date_object)

出力:

date_string = 21 June, 2018 date_object = 2018-06-21 00:00:00

%d日、%B月名フル、%Y年。


タイムゾーン認識

異なるゾーンで時刻表示・計算が必要なアプリでは、手動計算を避けpytzライブラリを使用。

from datetime import datetime import pytz local = datetime.now() print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S")) tz_NY = pytz.timezone('America/New_York') dt_NY = datetime.now(tz_NY) print("NY:", dt_NY.strftime("%m/%d/%Y, %H:%M:%S")) tz_London = pytz.timezone('Europe/London') dt_London = datetime.now(tz_London) print("London:", dt_London.strftime("%m/%d/%Y, %H:%M:%S"))

サンプル出力:

Local: 12/20/2018, 13:10:44 NY: 12/20/2018, 08:10:44 London: 12/20/2018, 13:10:44

datetime_NYとdatetime_Londonオブジェクトはタイムゾーン認識タイムスタンプを含みます。

Python

  1. Python データ型マスター: 実践ガイド
  2. Python 演算子完全マスター: 包括的ガイド
  3. Python pass文完全マスター: 実践ガイド
  4. Python 関数引数完全マスター: 位置引数・キーワード引数・デフォルト引数
  5. Python辞書完全ガイド:作成、操作、高度なテクニック
  6. Pythonイテレータ完全ガイド:仕組みと自作方法
  7. Pythonクロージャ解説:ネスト関数が変数を捕捉する仕組み
  8. Pythonで現在の日付と時刻を取得する実践ガイド
  9. Pythonで現在時刻とタイムゾーンデータを簡単に取得する
  10. Pythonのtime.sleep()をマスター:ベストプラクティス、マルチスレッド、実例
  11. Python 概要:高水準、読みやすい、インタラクティブ、オブジェクト指向