在Python中从当前日期和时间倒数一周之后? [英] Count down to a week later from current date and time in Python?

查看:223
本文介绍了在Python中从当前日期和时间倒数一周之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个运行时可以从用户计算机获取当前日期和时间的应用程序,然后在运行时倒数一周。

I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.

例如:

用户在06-06-2017 11:00:00运行该应用程序,它必须在一周后倒数到截止日期,并显示截止日期和时间,并倒计时还剩多少天,小时,分钟和秒。

The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.

编辑:

到目前为止,我只能获取日期和时间,并且时间通常每秒增加一次。我很难减少它。没有代码的最后一行,时间会减少,但不会自动更新。我还没有找到一种方法可以提前一周进行倒计时。

So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.

def updateTime():
    X = 1
    t = datetime.datetime.now()
    s = t.replace(microsecond=0)
    result = s - datetime.timedelta(seconds=X)
    future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
    lblTime.configure(text=result, font=("", 14))
    lblTime.after(100, updateTime)


推荐答案

您肯定要计算目标时间仅一次,而不是每次 updateTime 处理程序运行时都获得目标时间。此外,您可以简单地对datetime对象进行算术运算,以获取timedelta对象,然后可以将其显示在GUI中。

You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.

这里是一个将输出打印到的示例控制台。您可能可以根据需要对其进行调整,以使其在GUI中显示。

Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.

import datetime

target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)

def get_remaining_time():
    delta = target_time - datetime.datetime.now()

    hours = delta.seconds // 3600
    minutes = (delta.seconds % 3600) // 60
    seconds = delta.seconds % 60
    print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))


while True:
    get_remaining_time()

这篇关于在Python中从当前日期和时间倒数一周之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆