如何让用户输入日期并从中减去 [英] How To Have User Input Date and Subtract from It

查看:44
本文介绍了如何让用户输入日期并从中减去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是用户输入一个选定的日期,然后从当前日期中减去该日期,然后根据结果创建一个睡眠定时器.

What I want is a user input a selected date, and subtract that date from the current date, and then create a sleep timer according to the results.

from datetime import tzinfo, timedelta, datetime
def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date: mm/dd/yy: ")
        try:
            d1 = datetime.datetime.strptime(userIn, "%m/%d/%y")
            isValid=True
        except:
            print "Invalid Format!\n"
    return d1

t = (datetime.now() - d1).seconds

我当前的当前代码看起来像这样,但我不知道如何获取 d1 并从中减去当前日期.

My current current code looks like this, but I cannot figure out how to get d1 and subtract the current date from it.

推荐答案

您的代码有一些简单的错误.此版本有效(虽然我不确定您到底需要什么,但它应该能让您解决眼前的问题).

Your code has a few simple errors. This version works (though I'm not sure exactly what you need, it should get you past your immediate problem).

from datetime import datetime

def ObtainDate():
    while True:
        userIn = raw_input("Type Date: mm/dd/yy: ")
        try:
            return datetime.strptime(userIn, "%m/%d/%y")
        except ValueError:
            print "Invalid Format!\n"

t0 = datetime.now()
t1 = ObtainDate()
td = (t1 - t0)

print t0
print t1
print td
print td.total_seconds()

您的主要问题是您没有调用您的函数.我还将您的 while 循环简化为无限循环.除非引发错误,否则 return 语句将跳出循环.

Your main problem was that you were not calling your function. I have also simplified your while loop to an infinite loop. The return statement will break out of the loop unless it raises an error.

这篇关于如何让用户输入日期并从中减去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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