Pythonの時間処理モジュール:time、datetime、calendar

timeモジュール

時間の表現方法:タイムスタンプとは、1970年1月1日0時0分0秒からの経過秒数を整数または浮動小数点数で表す時間の表現方式です。

timeモジュールのインポート

import time


1. 現在のタイムスタンプを取得

current_time = time.time()
print(current_time)


2. タイムスタンプをUTC時間のタプルに変換

utc_time = time.gmtime(current_time)
print(utc_time)


3. タイムスタンプをローカル時間のタプルに変換

local_time = time.localtime(current_time)
print(local_time)


4. ローカル時間をタイムスタンプに変換

timestamp = time.mktime(local_time)
print(timestamp)


5. 時間タプルを文字列に変換

time_string = time.asctime(local_time)
print(time_string)


6. タイムスタンプを文字列に変換

formatted_time = time.ctime(current_time)
print(formatted_time)


書式指定文字列:

• %H 24時間制での時間 [0-23]
• %I 12時間制での時間 [01-12]
• %j 年間の日数 [001,366]
• %m 月 [0,12]
• %M 分 [0,59]
• %P 午前または午後 – AM or PM
• %S 秒 [0,61]
• %U 週が年間何週目か(日曜日を週の初日とする)
• %W 週が年間何週目か(月曜日を週の初日とする)
• %w 週内の曜日 [0,6](6は日曜日)
• %x 日付文字列表現:03/08/15
• %X 時刻文字列表現:23:22:08
• %y 2桁の年 [15]
• %Y 4桁の年 [2015]
• %z UTCとの時間差(ローカル時間の場合は空文字)
• %Z タイムゾーン名(ローカル時間の場合は空文字)

7. 時間タプルを指定された形式の文字列に変換

custom_format = time.strftime("%Y--%m--%b", local_time)
print(custom_format)


8. 文字列から時間タプルへの変換:time.strptime(文字列, 書式)

time_tuple = time.strptime(custom_format, "%Y--%m--%b")
print(time_tuple)


9. スリープ:プログラムの一時停止

time.sleep(3)


datetimeモジュール

datetimeモジュールはtimeよりも高度で、より直感的なインターフェースを持っています。datetimeはtimeをラップして、より多くの機能を提供します。

モジュールのインポート

import datetime


1. 現在の日時を取得:datetime.datetime.now()

current_datetime = datetime.datetime.now()
print(current_datetime)


2. 指定した日時を取得:datetime.datetime(年, 月, 日, 時, 分, 秒, マイクロ秒)

specific_date = datetime.datetime(2018, 12, 20, 10, 11, 10, 1223)
print(specific_date)


3. 日時オブジェクトを文字列に変換:time_object.strftime(書式)

date_string = current_datetime.strftime("%y-%m-%d")
print(date_string)


4. 文字列を日時オブジェクトに変換:datetime.datetime.strptime(文字列, 書式)

parsed_time = datetime.datetime.strptime(date_string, "%y-%m-%d")
print(parsed_time)


5. 日時計算:日時の差分を求める

start_time = datetime.datetime(2019, 8, 1, 1, 2, 2)
end_time = datetime.datetime(2019, 8, 5, 1, 8, 2)
duration = end_time - start_time
print(duration)
# 日数を取得
print(duration.days)
# 日数以外の秒数を取得
print(duration.seconds)


calendarモジュール

モジュールのインポート

import calendar


# 1. 特定年の特定月のカレンダーを取得:calendar.month(年, 月)

monthly_calendar = calendar.month(2019, 7)
print(monthly_calendar)


# 2. 特定年のカレンダーを取得:calendar.calendar(年)

print(calendar.calendar(2019))


# 3. 閏年判定:calendar.isleap(年) → True / False

print(calendar.isleap(2000))
print(calendar.isleap(2001))


# 4. 特定月の最初の曜日とその月の総日数を取得:calendar.monthrange(年, 月)

print(calendar.monthrange(2019, 6))


# 5. 特定月の日付を週単位のリストとして取得:calendar.monthcalendar(年, 月)

print(calendar.monthcalendar(2019, 6))

タグ: Python time datetime Calendar 時間処理

7月12日 17:41 投稿