How can I compare dates using Python? - python

If I have a hard coded date, how can I compare it to a date that is given by the user?
I want to eventually compare a persons birthday to see how old they are. Can someone point me in the right direction?

You'll want to use Python's standard library datetime module to parse and convert the "date given by the user" to a datetime.date instance and then subtract that from the current date, datetime.date.today(). For example:
>>> birthdate_str = raw_input('Enter your birthday (yyyy-mm-dd): ')
Enter your birthday (yyyy-mm-dd): 1981-08-04
>>> birthdatetime = datetime.datetime.strptime(birthdate_str, '%Y-%m-%d')
>>> birthdate = birthdatetime.date() # convert from datetime to just date
>>> age = datetime.date.today() - birthdate
>>> age
datetime.timedelta(11397)
age is a datetime.timedelta instance, and the 11397 is their age in days (available directly via age.days).
To get their age in years, you could do something like this:
>>> int(age.days / 365.24)
31

Related

could anyone identify the days python?

ask the user enter the date in the format YYYY-MM-DD
1.what age of user in days;
2.what day of week (in German language) was the birth.
import datetime
b = int(input('Enter your birthdate: '))
bb = datetime(b, '%Y-%m-%d')
a = datetime.date.today()
c = a-bb
print(c)
from datetime import datetime
d = input("Enter the date of birth: ")
print(d.strftime('%A'))
Your problem is trying to convert an input that's probably in YYYY-MM-DD format, into an int. This will not work in Python. Simply leave as a string and convert to a date.
Use setlocale to choose German for output.
from datetime import datetime
from datetime import date
# set language output to German
import locale
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
# convert a str to a date, subtract with current date to get # of days
date_time_str = input('Enter your birthdate: ')
bday = datetime.strptime(date_time_str, '%Y-%m-%d').date()
today = date.today()
print(today - bday)
# reuse the "bday" variable defined above, get day of week (in German)
print(bday.strftime('%A'))
Output:
730 days, 0:00:00
Mittwoch

I need To find how to subtract the current date by another date

So I am trying to make a script to tell you how long you have been alive. It al went good but I can’t find out how to subtract a birthday from the current date as shown in the total variable.
import time
## dd/mm/yyyy format
times=(time.strftime("%d/%m/%Y"))
day=(time.strftime("%d"))
month=(time.strftime("%m"))
year=(time.strftime("%Y"))
##questions
born_y=input('what year were you born')
born_m=input('what month')
born_d=input('what day')
##convert to decimal
current_time=int(year+'.'+month+'.'+day)
current_age=int(born_y+'.'+born_m+'.'+born_d)
##find age
total=current_time-current_age
print(total)
Try using datetime instead of time like this:
import datetime
year = input("What year were you born: ")
month = input("What month were you born: ")
day = input("What day were you born on: ")
born = datetime.datetime(int(year), int(month), int(day))
age = datetime.datetime.now() - born
print(age.days)
>>> 7549
You can then split thetimedelta object age up how you want, or just get the days from age.days.
Be aware that this won't work if the user inputs anything other than integers.

Printing multiple variables returned from single function

Take a look at my code:
def convert_date(date_int):
month = int(date_int / 1000000)
date_int = int(date_int - 1000000 * month)
days = int(date_int / 10000)
date_int = int(date_int - 10000 * days)
year = date_int
return days, month, year
print("*This part*".format(convert_date(
int(input("Enter a date in the format MMDDYYYY: ")))))
That "this part" is the part that I dont know how to phrase to print a new line like this from user input “05102017”:
10/05/2017
Also I would appreciate if someone could suggest a better way to manipulate this user input😢
I would strongly suggest you use the datetime library.
But if you want to do it by simply manipulating a string from user input, you don't need the "convert_date" function. You can simply do:
input_date = input("Enter a date in the format MMDDYYYY: ")
print("{}/{}/{}".format(input_date[:2], input_date[2:4], input_date[4:]))
>>> date = int(input("Enter a date in the format MMDDYYYY: "))
Enter a date in the format MMDDYYYY: 05102017
>>> date = convert_date(date) # your function
>>> date
(10, 5, 2017)
>>> print("{}/{}/{}".format(date[0], date[1], date[2]))
10/5/2017

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