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 versio
Solution 1:
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.
Solution 2:
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('...'))
Solution 3:
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
Post a Comment for "How To Find Difference Between Two Dates In Terms Of Day By Getting Date As User Input"