Python指针/advi

2024-05-18 06:12:15 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个被问到的问题,下面我将粘贴到目前为止的代码。任何建议都很好。不管我在做什么,请记住我的想法。你会怎么编码?无论如何,任何帮助都是非常感谢的!在

我想用%来计算,而不是把所有的都减去,但这两种方法都不重要。在

如果我早上6:52离开家,以轻松的速度跑1英里(每英里8:15),然后以速度跑3英里(每英里7:12),再以轻松速度跑1英里,我什么时候回家吃早餐?

 seconds = 1
 hours = seconds / (60*60)
 seconds = seconds - hours*60*60
 minutes = seconds / 60
 seconds = seconds - minutes *60

 time_left_house = 6 * hours + 52 * minutes

 miles_run_easy_pace = 2 * (8 * minutes + 15 * seconds)

 miles_run_fast_pace = 3 * (7 * minutes + 12 * seconds)


 total_time_run = miles_run_easy_pace + miles_run_fast_pace + time_left_house

 print total_time_run, "Total time run: " , hours, 'Hours: ', minutes, 'Minutes: ', seconds, 'Seconds: ‘

仅供参考,我使用的是python2.7.6


Tags: run代码time粘贴easyleft速度house
2条回答

你好像把代码搞混了。开头的部分看起来像是将total_time_run拆分为小时、分钟和秒的代码

把每件事都算作秒可能是个好主意。我用大写字母表示这些转换因子,以区分它们是常量

SECONDS = 1
MINUTES = 60 * SECONDS
HOURS = 60 * MINUTES

# All these results are in seconds

time_left_house = 6 * HOURS + 52 * MINUTES

miles_run_easy_pace = 2 * (8 * MINUTES + 15 * SECONDS)

miles_run_fast_pace = 3 * (7 * MINUTES + 12 * SECONDS)

total_time_run = miles_run_easy_pace + miles_run_fast_pace + time_left_house

# So we now have a big number of seconds to split into hours/minutes/seconds

hours = total_time_run // HOURS

# the left over part is minutes and seconds (still in seconds)

part_hour = total_time_run % HOURS
minutes = part_hour // MINUTES
seconds = part_hour % MINUTES

print "Total time run: {}, Hours: {}, Minutes: {}, Seconds: {}".format(
    total_time_run, hours, minutes, seconds)

您可能需要使用来自datetime模块的类:http://docs.python.org/2/library/datetime.html,例如timedelta。在

示例如下:)

>>> from datetime import datetime, timedelta, time
>>> time_left_house = datetime.combine(date.today(), time(hour = 6, minute = 52))
>>> miles_run_easy_pace = 2 * timedelta(minutes = 8, seconds = 15)
>>> miles_run_fast_pace = 3 * timedelta(minutes = 7, seconds = 12)
>>> total_time_run = time_left_house + miles_run_easy_pace + miles_run_fast_pace
>>> print total_time_run
2014-01-31 07:30:06
>>>

相关问题 更多 >