Argutus
Argutus

Reputation: 11

How To Have User Input Date and Subtract from It

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

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

Upvotes: 1

Views: 6937

Answers (2)

Graeme Stuart
Graeme Stuart

Reputation: 6053

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()

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.

Upvotes: 1

Brionius
Brionius

Reputation: 14098

Since you are importing the class using

from datetime import tzinfo, timedelta, datetime

you are no longer importing the whole datetime module under that name, but individual classes directly into your script's namespace. Therefore your input parsing statement should look like this:

d1 = datetime.strptime(userIn, "%m/%d/%y")  # You are no longer

The following will give you the difference in seconds between now and the entered time:

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

And as for the second part, there are many ways to implement a timer. One simple way is

import time
time.sleep(t)

EDIT

Here is the whole thing together:

from datetime import tzinfo, timedelta, datetime

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

t = (ObtainDate() - datetime.now()).total_seconds()
print t

Upvotes: 1

Related Questions