使用python实现将秒转化为天时分
在计算时间差的时候,比较容易得到timedelta这样的格式
比如:
>>> import datetime
>>> datetime.datetime.now()-datetime.datetime(2021,1,1)
datetime.timedelta(days=150, seconds=40790, microseconds=833309)
>>> a = datetime.datetime.now()-datetime.datetime(2021,1,1)
>>> a
datetime.timedelta(days=150, seconds=40806, microseconds=749774)
>>> str(a)
'150 days, 11:20:06.749774'
>>> a.days
150
>>> a.seconds
40806
>>>
这里如果仅仅是输出天数,就很容易得到,但是具体一点的信息显示的不是很友好
因此可以先利用函数将其全部转化为秒,然后再计算
>>> (datetime.datetime.now()-datetime.datetime(2021,1,1)).total_seconds()
13000936.085446
然后利用下面的函数就能转化为具体花费的多少时间
def seconds_to_dhms(seconds):
def _days(day):
return "{} days, ".format(day) if day > 1 else "{} day, ".format(day)
def _hours(hour):
return "{} hours, ".format(hour) if hour > 1 else "{} hour, ".format(hour)
def _minutes(minute):
return "{} minutes and ".format(minute) if minute > 1 else "{} minute and ".format(minute)
def _seconds(second):
return "{} seconds".format(second) if second > 1 else "{} second".format(second)
days = seconds // (3600 * 24)
hours = (seconds // 3600) % 24
minutes = (seconds // 60) % 60
seconds = seconds % 60
if days > 0 :
return _days(days)+_hours(hours)+_minutes(minutes)+_seconds(seconds)
if hours > 0 :
return _hours(hours)+_minutes(minutes)+_seconds(seconds)
if minutes > 0 :
return _minutes(minutes)+_seconds(seconds)
return _seconds(seconds)
举个例子:
> seconds_to_dhms(a)
'1 day, 0 hour, 1 minute and 2 seconds'
>>> a = 24*60*60*45 + 60*13+59
>>> seconds_to_dhms(a)
'45 days, 0 hour, 13 minutes and 59 seconds'
>>> a = 24*60*60*45 + 60*13+59 +60*34
>>> seconds_to_dhms(a)
'45 days, 0 hour, 47 minutes and 59 seconds'
>>> a = 24*60*60*45 + 60*13+59 +60*60*34
>>> seconds_to_dhms(a)
'46 days, 10 hours, 13 minutes and 59 seconds'
>>> a = 24*60*60*45 + 60*13+59 +60*60*14
>>> seconds_to_dhms(a)
'45 days, 14 hours, 13 minutes and 59 seconds'
这样单复数都有了,如果是中文显示,就更简单一点了,直接在最后格式化输出就好了,不用再定义里面的四个小函数了