Calculating remaining days between 2 dates inputed by user - python

I am trying to calculate the number of days between two dates where the user is inputing the dates but cannot find how to do it. I currently have this code:
from datetime import date
startdate = date(input("When do you intend to start?"))
enddate = date(input("When is your deadline?"))
numstudydays = enddate - startdate
print (numstudydays)
Thank you

In python, input() method accepts the input as a string variable. You can then typecast it into an integer using int() method. But you cannot typecast an entire tuple. i.e (year, month, day) in your case.
You can do it by getting all the values one by one.
from datetime import date
print("Enter intended start date details: ")
year = int(input('Year: '))
month = int(input('Month: '))
day = int(input('Day: '))
startdate = date(year, month, day)
print("Enter intended enddate details: ")
year = int(input('Year: '))
month = int(input('Month: '))
day = int(input('Day: '))
enddate = date(year, month, day)
numstudydays = enddate - startdate
print (numstudydays)
Hope that helps.

You are making an incorrect use of the datetime constructor. I revised your solution to handle user input in a simple and manageable way. A basic data validation is performed by the datetime.strptime factory method but there could be more (like checking, for example, that the end date always comes after the start date):
from datetime import datetime, date
start, end = None, None
while start is None:
rawinput = input("When do you intend to start? ")
try:
# %Y stands for a fully specified year, such as 2017, 1994, etc.
# %m for the integer representation of a month, e.g. 01, 06, 12
# and %d for the day of the month
# see https://docs.python.org/3/library/time.html#time.strftime for more
start = datetime.strptime(rawinput, "%Y %m %d")
except ValueError:
print("Input must be \"<year number> <month number> <day number>\"")
while end is None:
rawinput = input("When is your deadline? ")
try:
end = datetime.strptime(rawinput, "%Y %m %d")
except ValueError:
print("Input must be \"<year number> <month number> <day number>\"")
diff = end - start
print("You have %d days of time" % diff.days)
I did more than a couple of tests, and this is what resulted:
None#vacuum:~$ python3.6 ./test.py
When do you intend to start? 2017 01 32
Input must be "<year number> <month number> <day number>"
When do you intend to start? 2017 01 31
When is your deadline? 2017 02 30
Input must be "<year number> <month number> <day number>"
When is your deadline? 2017 02 28
You have 28 days of time

I think your biggest issue is how you retrieve the date.
date() function requires three integers, e.g. date(2017,10,10)
When you use input() you get a string:
input() #returns a string
You would also need to solve this by splitting the input somehow:
e.g.
"2017-10-12".split("-") # returns ["2017","10","12"]
[int(i) for i in "2017-10-12".split("-")] # returns [2017,10,12]
That means if you do this, you get a date:
date(*[int(i) for i in input("When is your deadline?").split("-")])
But what you really want in this case is to use strptime. Strptime() converts a string to a datetime by defining how it looks:
from datetime import datetime
datetime.strptime("20171012","%Y%m%d").date() # returns: datetime.date(2017, 10, 12)
Example of full script
from datetime import datetime
startdate_str = input("When do you intend to start? e.g.(2017-10-10)")
enddate_str = input("When is your deadline? e.g.(2017-10-11)")
startdate_dt = datetime.strptime(startdate_str,"%Y-%m-%d").date()
enddate_dt = datetime.strptime(enddate_str,"%Y-%m-%d").date()
numstudydays = enddate_dt - startdate_dt
print (numstudydays.days) # prints 1 for example inputs
Recommended links
The various kind of ways to format a string:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Related

Check if date is between two dates without year included

I have a datetime date in the format yyyy-mm-dd and I want to check if the date entered falls between for example May 15th and May 25th without including any year value.
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
import datetime
tripDate = datetime.datetime.strptime(tripDate_str, "%Y-%m-%d")
Well I guess the simplest approach is to use the month and day date class attributes
import datetime
tripDate = datetime.datetime.strptime('2022-05-15', "%Y-%m-%d")
start = datetime.datetime.strptime('2022-05-10', "%Y-%m-%d")
end = datetime.datetime.strptime('2022-05-20', "%Y-%m-%d")
if tripDate.month >= start.month and tripDate.month <= end.month and tripDate.day >= start.day and tripDate.day <= end.day:
print('Date in range')
else:
print('Date not in range')
There are many options to get the day of the year from a date. Use a search engine with keywords python day of year to find out which or just look here at stackoverflow ("Convert Year/Month/Day to Day of Year in Python"). The code below is using for this purpose dateObject.timetuple().tm_yday:
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
# tripDate_str = "2022-05-18"
## Finding day of year
from datetime import date
tripDate = date(*map(int, tripDate_str.split('-')))
tripDate_dayOfYear = tripDate.timetuple().tm_yday
print("Day of year: ", tripDate_dayOfYear, type(tripDate_dayOfYear))
dateRangeBeg_dayOfYear = date(tripDate.year, 5, 15).timetuple().tm_yday
dateRangeEnd_dayOfYear = date(tripDate.year, 5, 25).timetuple().tm_yday
if dateRangeBeg_dayOfYear <= tripDate_dayOfYear <= dateRangeEnd_dayOfYear:
print("tripDate falls into range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
else:
print("tripDate is outside range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
To avoid a problem with leap years tripDate.year is used in setting the values of dateRangeBeg_dayOfYear and dateRangeEnd_dayOfYear.

Convert int to date

I'm trying to convert yyyy/mm/dd to dd/mm/yyyy, from integer inputs.
When i've changed the pattern inside the parethesis from datetime.date(year, month, day), to datetime.date(day, month, year), it returns an Value error.
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(day, month, year)
return exp_date
ValueError: day is out of range for month
From the documentation:
class datetime.date(year, month, day)
This means you need to put the arguments in the right position, doesn't matter how you want to print it later.
This should work:
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(year, month, day)
return exp_date
Now let's print it formatted in dd/mm/yyyy:
d = acc_expiration()
f = d.strftime('%d/%m/%Y')
print(f) # prints it formatted dd/mm/yyyy
Your value error is because you are giving a year integer (integer bigger than 31) to the day argument, and for the year you are giving the day integer.
You are confusing the object from its presentation.
Look at the Python docs for Datetime (here)
The correct sequence for datetime.date is class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
Once you have a datetime object, you can format the output of it in a variety of ways to suit your needs.
Does that help?

how to find difference between two dates in terms of day by getting date as user input

I need to find the difference between two dates in terms of days by getting date as a user input. I tried to get date using raw_input but I'm getting an error. I'm using 2.7 version of python.
import time
from datetime import date
day1 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
diff = day2-day1
print diff
You'll need to parse those dates into something a little more meaningful. Use the datetime.datetime.strptime() method:
from datetime import datetime
day1 = raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = raw_input("enter the date in this format (yyyy:mm:dd)")
day1 = datetime.strptime(day1, '%Y:%m:%d').date()
day2 = datetime.strptime(day2, '%Y:%m:%d').date()
diff = day2 - day1
print diff.days
The datetime.datetime.date() method returns just the date portion of the resulting datetime object.
If you are expecting the input in the form "yyyy:mm:dd", you cannot simply cast it to int.
Besides strptime, you can parse the input by yourself.
day1 = [int(i) for i in raw_input('...').split(':')]
d1 = datetime.date(*day1)
day2 = [int(i) for i in raw_input('...').split(':')]
d2 = datetime.date(*day2)
diff = d2 - d1
print diff.days
Thanks to #JF Sebastian, even simpler way using lambda by defining:
str2date = lambda s: datetime.date(*map(int, s.split(':')))
Simply call:
date = str2date(raw_input('...'))
from datetime import date
import datetime
date1= datetime.date.today()
date_1=print(date1.strftime("The date of order: %d/%m/%Y"))
year = int(input('Enter a year: '))
month = int(input('Enter a month: '))
day = int(input('Enter a day: '))
date2 = datetime.date(year, month, day)
date_2= print(date2.strftime("Payment due date: %d/%m/%Y"))
difference=(date2-date1).days
print("The number of days for payment is: ", difference)
Its a program that allows a the user to find the difference between today's date and the input date from the user, in DAYS

Python 3.2 input date function

I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)

Python: Adding 3 weeks to any date

I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go

Categories