在python中的datetime并且摆脱90分钟“10”次

时间:2017-05-05 20:15:24

标签: python datetime

我正在制作一个程序,该程序应该在唤醒时间内唤醒,然后它应该减去90分钟(1小时30分钟) 10次​​获得你应该去睡觉的时间,例如如果我想在11:30醒来,那么它会让我回到10:00 - 8:30 - 7:00 - 5:30等等。

下面是我的代码,最后一部分是不能使用for循环的代码,因为我收到错误“replace()没有关键字参数”

import datetime

#Gets the time you would like to wake up at

user_input = input("Write a time you'd like to wake up at like \"11:30\": ")

#Cuts the first piece off so if it were 11:30, this would get 11

first_user_time = user_input[0:2]
first_user_time = int(first_user_time)

#Cuts the second piece off so if it were 11:30, this would get 30

second_user_time = user_input[3:5]
second_user_time = int(second_user_time)

#Gets the current time today

this_time = datetime.datetime.today()

#Replaces the time of today to your set "Wake up time"

new_time = this_time.replace(hour=first_user_time ,minute=second_user_time).strftime("%H:%M")

#Prints out your wake up time

print("Wake Up Time:", new_time)

#This one is not working for me and I need help with this one
#It's supposed to get 10 different times where you could go to bed to wake up fresh at "11:30"

for i in range(10):
    the_hour = -1
    the_minute = -30

    sleep_time = new_time.replace(hour= the_hour, minute=the_minute).strftime("%H:%M")
    print("Your Sleep Times:", sleep_time)

2 个答案:

答案 0 :(得分:0)

这是strftime

之后的字符串
new_time = this_time.replace(hour=first_user_time ,minute=second_user_time).strftime("%H:%M")

字符串 replace不接受关键字参数

for i in range(10):
    the_hour = -1
    the_minute = -30

    # Error here
    sleep_time = new_time.replace(hour= the_hour

因此,删除strftime,直到您确实要显示该值,然后才

答案 1 :(得分:0)

问题是,正如cricket_007所指出的,当它是一个字符串时,你不能将关键字参数传递给.replace()。这适用于您之前的.replace(),因为它是一个日期对象,并且有一个替换小时,分钟等的方法。相同的名称,但实际上有两个不同的功能。

你得到的另一个新问题是因为它试图将分钟设置为-30,这显然是不可能的。您应该使用datetime.timedelta()函数来代替。

尝试以下更新:

将new_time保留为日期时间对象,以便您可以正确操作

#Replaces the time of today to your set "Wake up time"

new_time = this_time.replace(hour=first_user_time ,minute=second_user_time)

每次要显示时,请拨打strftime()

#Prints out your wake up time

print("Wake Up Time:", new_time.strftime("%H:%M"))

在循环中,使用timedeltadatetime对象进行正确的减法,并在向用户显示时再次使用strftime()

for i in range(10):
    new_time = new_time - datetime.timedelta(hours=1, minutes=30)
    print("Your Sleep Times:", new_time.strftime("%H:%M"))