好的,所以,我是Python的新手(这是我的第一个程序)。我正在尝试制作倒数计时器,倒计时到任何给定的日期。我有一些(简单)部分可行,我的下一步问题包括:我是否需要将给定时间存储在列表中,然后解析它并将年份,日期等存储在单独的变量中?我可以在Python中为另一个日期减去一个日期给我一些时间吗?
from datetime import datetime
current_time = (str(datetime.now()))
print("The current time is " + current_time)
target_day = input("What date are you waiting for (day/month/year format, please)?")
time_left = target_time - current_time
while current_time:
if current_time == target time:
break
print("It's time!")
print(\rtime_left)
print("You have " + weeks + "weeks, " + days + "days," + hours + "hours, and " + minutes.")
答案 0 :(得分:1)
首先获取两次的datetime
对象并减去对象以获取timedelta
类型的对象。然后调用 timedelta 对象的total_seconds(..)
函数以获得以秒为单位的时差。例如:
>>> from datetime import datetime
>>> target_time = '18/03/2022'
>>> target_datetime = datetime.strptime(target_time, '%M/%d/%Y')
>>> current_datetime = datetime.now() # No need to convert it to string
>>> time_left = target_datetime - current_datetime # return `timedelta` object
# returns total seconds
>>> time_left.total_seconds()
139037207.03403
答案 1 :(得分:0)
time_left = target_time - current_time
你非常接近。让您感到沮丧的是,您仍然需要将target_time,str转换为日期时间。然后,您将从减法中获得timedelta结果,您将发现它非常有用。使用此function:
解析日期target_time = datetime.strptime(text_from_user, '%d-%b-%Y')
答案 2 :(得分:0)
您需要做的就是打印出等待时间和现在时间之间的差异。这可以通过简单的减法来轻松完成,方法是将所有内容转换为秒,然后减去以获得没有任何结转的秒数。接下来只需将秒转换为年,月,日,分和秒,只需使用循环首先将秒除以(mod)60并将余数除以秒,然后将分钟除以60,其余为分钟再次,然后除以24得到剩余的小时等等......
另外,我建议设置一个间隔,否则你的程序会在继续之前尽可能快地打印相同的日期,而不是你可以设置一个间隔,否则你的循环将继续检查自己并打印你有“这个长期离开“比它需要的时间多。
当然有更简单的方法,这只是为了详细解释手动执行的步骤,以帮助您理解而不是仅仅粘贴在一行而不理解它。
我希望这会有所帮助。