冬雪雪冬 发表于 2018-1-15 18:55:30

Python:每日一题 142

本帖最后由 冬雪雪冬 于 2018-2-4 20:36 编辑

我们的玩法做了一下改变:

1. 楼主不再提供答案。
2. 请大家先独立思考”,再参考其他鱼油的解答,这样才有助于自己编程水平的提高。
3. 鼓励大家积极答题,奖励的期限为出题后24小时内。
4. 根据答案的质量给予1~3鱼币的奖励。

题目:
给出两个时间算出时间差(以秒计),如果结束时间小于开始时间则结束时间在下一天,开始和结束时间不超过1天。
例如:
start = 17:55:31
stop = 4:21:57
时间差为:37586s

shigure_takimi 发表于 2018-1-15 19:30:06

本帖最后由 shigure_takimi 于 2018-1-15 19:41 编辑

start = '17:55:31'
stop = '4:21:57'

def getSeconds(start, stop):
        start =
        stop =
        startSeconds = start*3600 + start*60 + start
        stopSeconds = stop*3600 + stop*60 + stop
        if stop<start or (stop==start and stop<start) or (stop==start and stop==start and stop<start):
                stopSeconds += 24*3600
        return stopSeconds - startSeconds

print('Start time:', start)
print('Stop time:', stop)
print('Time passed:', getSeconds(start, stop), 'seconds.')
       

##    Start time: 17:55:31
##    Stop time: 4:21:57
##    Time passed: 37586 seconds.

wyp02033 发表于 2018-1-15 21:07:00

本帖最后由 wyp02033 于 2018-1-17 22:24 编辑

def main():
    start = "17:55:31"
    stop = "4:21:57"
    start_time =
    stop_time =
    time_difference =
    for i in range(3):
      time_difference = stop_time - start_time
    time_difference.reverse()
    for i in range(2):
      if time_difference < 0:
            time_difference += 60
            time_difference -= 1
    if time_difference[-1] < 0:
      time_difference[-1] += 24

    all_seconds = 0
    for i in range(3):
      all_seconds += time_difference * 60 ** i

    print("时差为:%d s" % all_seconds)

if __name__ == '__main__':
    main()
结果:37586 s

Nina_cll 发表于 2018-1-15 21:30:50

def change(time):
    hour,minter,second=time.split(':')
    time_second=3600*int(hour)+60*int(minter)+int(second)
    return time_second
start=input('请输入开始时间:')
stop=input('请输入结束时间:')
t1=change(start)
t2=change(stop)
if t2>t1:
    t=t2 -t1
else:
    t=86400-t1+t2
    print('已经是第二天')
print('时间差为%ds'% t)

请输入开始时间:17:55:31
请输入结束时间:4:21:57
已经是第二天
时间差为37586s

Elastcio 发表于 2018-1-15 22:27:28

from datetime import datetime, timedelta

start = "17:55:31"
stop = "4:21:57"


start_time = datetime.strptime(start, "%H:%M:%S")

stop_time = datetime.strptime(stop, "%H:%M:%S")
delta = start_time - stop_time
if start_time < stop_time:
    print(delta.total_seconds())
else:
    delta = timedelta(seconds=86400) - delta
    print(delta.total_seconds())

graceasyi 发表于 2018-1-16 03:17:15

感觉有点笨。。{:5_103:}

start = "17:55:31"
stop = "4:21:57"
start_list =
stop_list =

if stop_list - start_list < 0:
      h_diff = stop_list - start_list + 24
else:
      h_diff = stop_list - start_list

diff = h_diff*60*60 + (stop_list - start_list)*60 + (stop_list - start_list)
print(diff)


结果:37586

空巷无人故人叹 发表于 2018-1-16 09:39:22

import easygui

def gettime(msg):
    while True:
      title = 'time'
      a = easygui.enterbox(msg,title)
      b = a.split(':')
      for i in range(0,3):
            b = int(b)
            if b >= 60 :
                msg = '输入时间有误,请重新输入'
                easygui.msgbox(msg,title)
      if (b < 60) and (b < 60) and (b < 60):
            return b

start = gettime('请输入开始时间(以冒号间隔)')
stop = gettime('请输入结束时间(以冒号间隔)')

if start > stop:
    stop = stop + 24

start_seconds = start * 60 * 60 + start * 60 + start
stop_seconds = stop * 60 * 60 + stop * 60 + stop
interval_seconds = stop_seconds - start_seconds

msg = '时间间隔为:{a}秒'
msg = msg.format(a = interval_seconds)
title = 'time'
easygui.msgbox(msg,title)

lovesword 发表于 2018-1-16 09:57:34

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime importdatetime
start = '17:55:31'
stop = '4:21:57'
print(datetime.strptime(stop,'%H:%M:%S')-datetime.strptime(start,'%H:%M:%S')).seconds
------
res:37586

jfmlj 发表于 2018-1-16 10:19:05

start=input('start')
stop=input('stop')
#读取时,分,秒
def turn(time):
    start1=time.partition(':')
    h1=int(start1)
    start1=start1.partition(':')
    m1=int(start1)
    s1=int(start1)
    return h1,m1,s1

start=turn(start)
stop=turn(stop)

time1=start*3600+start*60+start
time2=stop*3600+stop*60+stop

if time2>=time1:
    time=time2-time1
else:
    time=24*3600+(time2-time1)


print('时间差为'+str(time)+'s')

jack_9957 发表于 2018-1-16 10:22:57

start = '17:55:31'
stop = '17:21:57'
start = start.split(":")       #先去掉:,变成str的列表
stop = stop.split(":")
start_ = []   #新建空列表
stop_ = []
for i in start:   #将str转为int,添加到空列表
    i = int(i)
    start_.append(i)
for i in stop:
    i = int(i)
    stop_.append(i)
print(start_,stop_)
all_start = eval('(start_)*3600 + start_*60 + start_')
all_stop = eval('(stop_)*3600 + stop_*60 + stop_')
if all_stop < all_start:    #如果结束时间小于开始时间,结束时间就在下一天,要加上一天的秒数
    daytime = 24*3600
    print((all_stop+daytime)-all_start)
else:
    print(all_stop - all_start)

lihw 发表于 2018-1-16 11:07:25


import datetime
start='17:55:31'
end='4:21:57'
st= datetime.datetime.strptime(start,"%H:%M:%S")
et= datetime.datetime.strptime(end,"%H:%M:%S")

print((et-st).seconds,end='')
print('s')

大头目 发表于 2018-1-16 11:42:53

print('''给出两个时间算出时间差(以秒计),如果结束时间小于开始时间则结束时间在下一天,开始和结束时间不超过1天''')
start1 = input('请输入开始时间(例如15:24:33):')
while (':' not in start1) or (len(start1) > 8):
        print('请输入格式有误')
        start1 = input('请输入开始时间(例如15:24:33):')
stop1 = input('请输入结束时间(例如3:24:33):')
while (':' not in stop1) or (len(stop1) > 8):
        print('请输入格式有误')
        start1 = input('请输入开始时间(例如15:24:33):')

start1 = start1.split(':')
stop1 = stop1.split(':')

#print(start1)

for i in range(3):
        start1=int(start1)
        stop1=int(stop1)
#print(start1)
second1 = start1 * 3600 + start1 * 60 + start1
second2 = stop1 * 3600 + stop1 * 60 + stop1

#print(second1 , second2)
if second1 >= second2:
        result = second2 - second1 + 24 * 3600
else:
        result = second2 - second1
print('时间差为:{0}s'.format(result))
print('时间差为:%ds'%(result))

cnkizy 发表于 2018-1-16 12:02:42

#!usr/bin/python3
import datetime
#输入时间
Dstart=datetime.datetime.strptime(input("start="),'%H:%M:%S')
Dstop=datetime.datetime.strptime(input("stop="),'%H:%M:%S')
#如果结束时间小于开始时间那么结束时间加一天
if Dstop<Dstart:
        Dstop = Dstop + datetime.timedelta(days=1)
result = (Dstop - Dstart).total_seconds()
print(result)
{:10_249:}py的时间戳课真麻烦,用过c#就知道c#处理时间真的很爽很丝滑。

jerryxjr1220 发表于 2018-1-16 13:28:53

start = '17:55:31'
stop = '4:21:57'
from datetime import datetime, timedelta
st = datetime.strptime(start,'%H:%M:%S')
sp = datetime.strptime(stop,'%H:%M:%S')
td = (sp-st).seconds if (sp-st).seconds>0 else (sp-st+timedelta(days=1)).seconds
print(td)

mq24 发表于 2018-1-16 13:40:40

a

vanche1212 发表于 2018-1-16 14:06:09

import time

class CalTimer:
   
    def __init__(self):
      self.begin = ''

    '''
    函数名:start
    参数:begin:开始时间
    返回值:None
    功能:开始计时
    '''
    def start(self):
      self.begin = time.localtime() #获取时分秒
      print('开始计时')
      

    '''
    函数名:stop
    参数:end:结束时间
    返回值:None
    功能:结束计时
    '''
    def stop(self):
      if not self.begin:
            print('please start first!')

      end = time.localtime() #获取时分秒
      
      timeLi = []
      timeTag = ['时', '分', '秒']
      for index, item in enumerate(timeTag):
            tmp = end - self.begin
            timeLi.append(tmp)

      res = str(timeLi*3600 + timeLi*60 + timeLi)
      print('结束计时,总耗时:' + res + '秒')

      
if __name__ == '__main__':
    a = CalTimer()
    a.start()
    time.sleep(30)
    a.stop()
      

h20060304 发表于 2018-1-16 14:49:56

start = '17:55:31'
end = '4:21:57'

start = map(lambda x:int(x),start.split(':'))
end = map(lambda x:int(x),end.split(':'))

for k in range(-1,-4,-1):
    if end < start:
      if k != -3:
            end += 60
            end -= 1
      else:
            end += 24

def second(x,y):
    return 60*x + y

divide = reduce(second, map(lambda x, y: x - y, end, start))

print divide

solomonxian 发表于 2018-1-16 18:28:42

不超过1天这个限制条件太方便了,手动
def fun(t1, t2):
    times = [sum(60**(2-i)*int(j) for i,j in enumerate(time.split(":")))
             for time in (t1, t2)]
    return "{}s".format((times - times) % 86400)
print(fun("17:55:31", "4:21:57"))
datetime也很快
import datetime

def fun2(t1, t2):
    t1 = datetime.datetime.strptime(t1, "%H:%M:%S")
    t2 = datetime.datetime.strptime(t2, "%H:%M:%S")
    return (t2 - t1).total_seconds() % 86400
print(fun2("17:55:31", "4:21:57"))
久没用过,小小的写个类{:10_245:}
class timedelta:

    def __init__(self, hours=0, minutes=0, seconds=0):
      self.hours = hours
      self.minutes = minutes
      self.seconds = seconds
      self.time = self.hours * 3600 + self.minutes * 60 + self.seconds
      
    def __sub__(self, other):
      return (self.time - other.time) % 86400

start = timedelta(17, 55, 31)
stop = timedelta(4, 21, 57)
print(stop - start)

wojiaodabai 发表于 2018-1-17 10:36:00

from datetime import datetime,timedelta

start = '17:55:31'
stop ='4:21:57'

d1=datetime.strptime(start,"%H:%M:%S")
d2=datetime.strptime(stop,'%H:%M:%S')

if d2>d1:
    print((d2-d1).seconds)
else:
    print((d2+timedelta(days=1)-d1).seconds)

久疤K 发表于 2018-1-17 12:43:36

'''
:号分割, 自行计算
'''

# 偏差
D = 3600 * 24

def time2seconds(time):
    time =
    return time*3600 + time*60 + time

def fun(start, stop):
    start = time2seconds(start)
    stop = time2seconds(stop)
    res = stop - start
    res += 0 if res >= 0 else D
    return res

def main():
    start = '17:55:31'
    stop = '4:21:57'
    print('start =',start)
    print('stop =',stop)
    print("时间差为:", fun(start,stop),'s')

if __name__ == "__main__":
    main()
结果:
start = 17:55:31
stop = 4:21:57
时间差为: 37586 s
页: [1] 2 3
查看完整版本: Python:每日一题 142