Skip to content Skip to sidebar Skip to footer

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, time

Solution 1:

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 timetime.sleep(t)

EDIT

Here is the whole thing together:

from datetime import tzinfo, timedelta, datetime

defObtainDate():
    isValid=Falsewhilenot isValid:
        userIn = raw_input("Type Date: mm/dd/yy: ")
        try:
            d1 = datetime.strptime(userIn, "%m/%d/%y")
            isValid=Trueexcept:
            print"Invalid Format!\n"return d1

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

Solution 2:

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

defObtainDate():
    whileTrue:
        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.

Post a Comment for "How To Have User Input Date And Subtract From It"