Python 秒数と分・時間・日数の相互変換方法【完全解説】
Pythonで時間の単位変換を行う方法を、基本的な計算からdatetimeモジュールの活用まで詳しく解説します。秒数から分・時間・日数への変換と、その逆変換の実装方法を学びましょう。
目次
基本的な時間単位の定数
# 時間単位の定数定義
SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 60 * 60 # 3600
SECONDS_PER_DAY = 60 * 60 * 24 # 86400
SECONDS_PER_WEEK = 60 * 60 * 24 * 7 # 604800
print(f"1分: {SECONDS_PER_MINUTE}秒")
print(f"1時間: {SECONDS_PER_HOUR}秒")
print(f"1日: {SECONDS_PER_DAY}秒")
print(f"1週間: {SECONDS_PER_WEEK}秒")
秒数から他の単位への変換
基本的な変換関数
def seconds_to_units(seconds):
"""秒数を日、時間、分、秒に分割"""
days = seconds // 86400
hours = (seconds % 86400) // 3600
minutes = (seconds % 3600) // 60
remaining_seconds = seconds % 60
return {
'days': int(days),
'hours': int(hours),
'minutes': int(minutes),
'seconds': int(remaining_seconds)
}
# 使用例
total_seconds = 93784 # 1日2時間3分4秒
result = seconds_to_units(total_seconds)
print(f"{result['days']}日 {result['hours']}時間 {result['minutes']}分 {result['seconds']}秒")
個別の変換関数
def seconds_to_minutes(seconds):
"""秒を分に変換"""
return seconds / 60
def seconds_to_hours(seconds):
"""秒を時間に変換"""
return seconds / 3600
def seconds_to_days(seconds):
"""秒を日に変換"""
return seconds / 86400
# 使用例
seconds = 7200
print(f"{seconds}秒 = {seconds_to_minutes(seconds)}分") # 120分
print(f"{seconds}秒 = {seconds_to_hours(seconds)}時間") # 2時間
print(f"{seconds}秒 = {seconds_to_days(seconds)}日") # 0.083日
他の単位から秒数への変換
基本的な変換関数
def minutes_to_seconds(minutes):
"""分を秒に変換"""
return minutes * 60
def hours_to_seconds(hours):
"""時間を秒に変換"""
return hours * 3600
def days_to_seconds(days):
"""日を秒に変換"""
return days * 86400
# 使用例
print(f"5分 = {minutes_to_seconds(5)}秒") # 300秒
print(f"2時間 = {hours_to_seconds(2)}秒") # 7200秒
print(f"3日 = {days_to_seconds(3)}秒") # 259200秒
複合単位の変換
def time_to_seconds(days=0, hours=0, minutes=0, seconds=0):
"""日、時間、分、秒の組み合わせを総秒数に変換"""
total_seconds = (
days * 86400 +
hours * 3600 +
minutes * 60 +
seconds
)
return total_seconds
# 使用例
total = time_to_seconds(days=1, hours=2, minutes=30, seconds=45)
print(f"1日2時間30分45秒 = {total}秒") # 95445秒
timedeltaを使用した変換
timedeltaオブジェクトの作成と変換
from datetime import timedelta
# timedeltaオブジェクトから秒数を取得
td = timedelta(days=1, hours=2, minutes=30, seconds=45)
total_seconds = td.total_seconds()
print(f"総秒数: {total_seconds}") # 95445.0
# 秒数からtimedeltaオブジェクトを作成
seconds = 93784
td = timedelta(seconds=seconds)
print(f"日数: {td.days}")
print(f"秒数: {td.seconds}") # 残りの秒数(86400未満)
timedeltaの属性を活用
from datetime import timedelta
def timedelta_breakdown(td):
"""timedeltaオブジェクトを詳細に分解"""
total_seconds = int(td.total_seconds())
days = td.days
hours = td.seconds // 3600
minutes = (td.seconds % 3600) // 60
seconds = td.seconds % 60
return {
'total_seconds': total_seconds,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
}
# 使用例
td = timedelta(seconds=266545) # 3日2時間2分25秒
breakdown = timedelta_breakdown(td)
print(f"総秒数: {breakdown['total_seconds']}")
print(f"{breakdown['days']}日 {breakdown['hours']}時間 {breakdown['minutes']}分 {breakdown['seconds']}秒")
人間が読みやすい形式への変換
動的な単位選択
def human_readable_time(seconds):
"""秒数を人間が読みやすい形式に変換"""
if seconds < 60:
return f"{seconds:.1f}秒"
elif seconds < 3600:
minutes = seconds / 60
return f"{minutes:.1f}分"
elif seconds < 86400:
hours = seconds / 3600
return f"{hours:.1f}時間"
else:
days = seconds / 86400
return f"{days:.1f}日"
# 使用例
test_values = [30, 150, 3700, 90000]
for value in test_values:
print(f"{value}秒 = {human_readable_time(value)}")
詳細な表示形式
def format_duration(seconds, show_all=False):
"""秒数を詳細な期間表示に変換"""
units = [
('年', 365 * 24 * 3600),
('月', 30 * 24 * 3600),
('週', 7 * 24 * 3600),
('日', 24 * 3600),
('時間', 3600),
('分', 60),
('秒', 1)
]
result = []
remaining = int(seconds)
for unit_name, unit_seconds in units:
if remaining >= unit_seconds:
count = remaining // unit_seconds
remaining %= unit_seconds
result.append(f"{count}{unit_name}")
elif show_all and result: # 途中の0を表示
result.append(f"0{unit_name}")
return ' '.join(result) if result else "0秒"
# 使用例
durations = [3661, 266545, 31536000]
for duration in durations:
print(f"{duration}秒 = {format_duration(duration)}")
実用的な応用例
処理時間の測定と表示
import time
from datetime import datetime, timedelta
class Timer:
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
self.start_time = time.time()
print("タイマー開始")
def stop(self):
self.end_time = time.time()
elapsed = self.end_time - self.start_time
print(f"経過時間: {format_duration(elapsed)}")
return elapsed
# 使用例
timer = Timer()
timer.start()
time.sleep(2.5)
elapsed = timer.stop()
動画の長さの管理
def video_duration_manager():
"""動画の長さを管理するクラス例"""
videos = [
{'title': 'Video 1', 'duration_seconds': 300}, # 5分
{'title': 'Video 2', 'duration_seconds': 3661}, # 1時間1分1秒
{'title': 'Video 3', 'duration_seconds': 7200}, # 2時間
]
total_seconds = sum(video['duration_seconds'] for video in videos)
print("動画リスト:")
for video in videos:
duration = format_duration(video['duration_seconds'])
print(f" {video['title']}: {duration}")
print(f"\n総再生時間: {format_duration(total_seconds)}")
video_duration_manager()
ワークタイム計算
def calculate_work_hours(time_entries):
"""勤務時間を計算"""
total_seconds = 0
for entry in time_entries:
start = entry['start']
end = entry['end']
work_seconds = (end - start).total_seconds()
total_seconds += work_seconds
print(f"{start.strftime('%m/%d')} {work_seconds/3600:.1f}時間")
print(f"合計: {format_duration(total_seconds)}")
return total_seconds
# 使用例(サンプルデータ)
from datetime import datetime
work_data = [
{
'start': datetime(2024, 1, 15, 9, 0),
'end': datetime(2024, 1, 15, 17, 30)
},
{
'start': datetime(2024, 1, 16, 10, 0),
'end': datetime(2024, 1, 16, 18, 15)
}
]
total_work_seconds = calculate_work_hours(work_data)
高精度な時間変換
小数点以下の処理
import math
def precise_time_conversion(seconds, precision=2):
"""高精度な時間変換"""
days = seconds / 86400
hours = seconds / 3600
minutes = seconds / 60
return {
'days': round(days, precision),
'hours': round(hours, precision),
'minutes': round(minutes, precision),
'seconds': round(seconds, precision)
}
# 使用例
seconds = 3661.547
conversions = precise_time_conversion(seconds, 3)
print(f"{seconds}秒 =")
print(f" {conversions['days']}日")
print(f" {conversions['hours']}時間")
print(f" {conversions['minutes']}分")
科学記法での表示
def scientific_time_display(seconds):
"""大きな秒数を科学記法で表示"""
units = [
('ミリ秒', 1e-3),
('秒', 1),
('分', 60),
('時間', 3600),
('日', 86400),
('年', 365.25 * 86400)
]
for unit_name, unit_value in units:
converted = seconds / unit_value
if 1 <= converted < 1000 or unit_name == '年':
return f"{converted:.2e} {unit_name}"
return f"{seconds:.2e} 秒"
# 使用例
large_values = [1e6, 1e9, 1e12]
for value in large_values:
print(f"{value:.0e}秒 = {scientific_time_display(value)}")
まとめ
- 基本変換:乗算・除算による単位変換
- timedelta活用:Pythonの標準的な時間差オブジェクト
- 人間可読形式:動的な単位選択で見やすい表示
- 実用例:タイマー、動画管理、勤務時間計算
- 高精度処理:小数点以下や科学記法での表示
これらの方法を活用することで、Pythonでの時間単位変換が効率的に行えます。
■らくらくPython塾 – 読むだけでマスター
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座



