Python unittest, datetime - python

My problem is:
In my following test, everything is working today but not will work tomorrow, I'm a beginner and did try a lot of options, but I failed, I,m trying pass "now" as a parameter but with no success until now.
I have to stop the "datetime.now()" and put one fixed date to can test all variations.
I had god progress until here, but I'm stuck on this
Can you help me, please?
Thank you.
Flavio
import unittest
from datetime import datetime
def get_last_name_and_birthday(name, d):
x = name.split()
dob = d.split("-")
year, month, day = int(dob[2]), int(dob[1]), int(dob[0])
user_birthday = datetime(year, month, day)
return x[-1], user_birthday
def calc_days(user_birthday):
now = datetime.now()
if user_birthday < now:
birthday = datetime(now.year + 1, user_birthday.month, user_birthday.day)
return (birthday - now).days + 1
else:
birthday = datetime(now.year, user_birthday.month, user_birthday.day)
return (birthday - now).days + 1
def generate_output(last_name, cd):
if cd == 365:
return "Hello Mr " + last_name + " Happy Birthday"
elif cd < 365:
return "Hello Mr " + last_name + " your birthday is in " + str(cd) + " days"
else:
return "Hello Mr " + last_name + " your birthday is in " + str(cd - 365) + " days"
def process_name_and_birthday(name, dob):
last_name, user_birthday = get_last_name_and_birthday(name, dob)
cd = calc_days(user_birthday)
return generate_output(last_name, cd)
#name = input("type your full name: ")
#dob = input("type your date of birthday(dd-mm-yy): ")
#print(process_name_and_birthday(name, dob))
class BirthdayTest(unittest.TestCase):
def test_same_day_birthday(self):
self.assertEqual("Hello Mr Oliveira Happy Birthday", process_name_and_birthday("Flavio Oliveira", "11-06-1990"))
class DaysToBirthdayTest(unittest.TestCase):
def test_days_to_birthday(self):
self.assertEqual("Hello Mr Oliveira your birthday is in 9 days", process_name_and_birthday("Flavio Oliveira", "20-06-1978"))
class DaysToPassedBirthdayTest(unittest.TestCase):
def test_how_many_days_passed_birthday(self):
self.assertEqual("Hello Mr Oliveira your birthday is in 364 days", process_name_and_birthday("Flavio Oliveira", "10-06-1978"))
unittest.main()

Add the following three lines under your import of datetime:
from unittest.mock import Mock
datetime = Mock(wraps=datetime)
datetime.now.return_value = datetime(2020, 6, 11, 20)
There is more information about the mock module here: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock

Related

What do we need to do to fix this equation so that it works in our Python code?

Assignment and code below...
I am assisting my son with his homework. I know coding, but not Python. He has gotten this far and has asked me to jump in to assist and I am stumped. I believe that the equation for the total take-home salary is too long, but I am not sure what to do to help. The code works as is, but when we try to switch the "...will take home $" + str(emp_1.salary) + ", after taxes." with "...will take home $" + str(emp_1.apply_taxes()) + ", after taxes." for both emp_1 and emp_2 we get an error that apply_taxes is not defined. all we need to do is get the equation to work and we will be good. Any suggestions would be greatly appreciated!
Thank you!!
This is the assignment:
Include to class variables that will account for the federal tax rate (0.2) and the state tax rate (0.0314)
Using these variables, add a method to the init method that will deduct BOTH federal and state taxes from the employee salary.
Using proper concatenation, output both the first employee's salary AND what the employee's take home pay will be after taxes are deducted.
Do the same for the second employee.
This is the code that we have:
class Employee:
fed_tax = float(.2)
state_tax = float(.0314)
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_taxes(self):
self.salary = int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print("The employee, " + emp_1.name + ", salary is $" + str(emp_1.salary) + ".")
print("Employee " + emp_1.name + " will take home $" + str(emp_1.salary) + ", after taxes.")
print("The employee, " + emp_2.name + ", salary is $" + str(emp_2.salary) + ".")
print("Employee " + emp_2.name + " will take home $" + str(emp_2.salary) + ", after taxes.")
you are not calling apply taxes anywhere:
Try something like:
class Employee:
fed_tax = 0.2
state_tax = 0.0314
def __init__(self, name, salary):
self.name = name
self.salary = salary
self.post_taxed_salary = self.apply_taxes()
def apply_taxes(self):
return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print('employee {} has salary of {} and after taxes {}'.format(emp_1.name, emp_1.salary, emp_1.post_taxed_salary))
Returns: employee Isaac Soiffer has salary of 50000 and after taxes 38430
On a note, because saalary is an attribute, you can make post_taxed_salary a property, e.g.
class Employee:
fed_tax = 0.2
state_tax = 0.0314
def __init__(self, name, salary):
self.name = name
self.salary = salary
#property
def post_taxed_salary(self):
return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
Should work as well

Calculating age in python

I am attempting to create a code where the user is asked for their date of birth and today's date in order to determine their age. What I have written so far is:
print("Your date of birth (mm dd yyyy)")
Date_of_birth = input("--->")
print("Today's date: (mm dd yyyy)")
Todays_date = input("--->")
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(Date_of_birth)
However it is not running like I would hope. Could someone explain to me what I am doing wrong?
So close!
You need to convert the string into a datetime object before you can do calculations on it - see datetime.datetime.strptime().
For your date input, you need to do:
datetime.strptime(input_text, "%d %m %Y")
#!/usr/bin/env python3
from datetime import datetime, date
print("Your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print(age)
PS: I urge you to use a sensible order of input - dd mm yyyy or the ISO standard yyyy mm dd
This should work :)
from datetime import date
def ask_for_date(name):
data = raw_input('Enter ' + name + ' (yyyy mm dd): ').split(' ')
try:
return date(int(data[0]), int(data[1]), int(data[2]))
except Exception as e:
print(e)
print('Invalid input. Follow the given format')
ask_for_date(name)
def calculate_age():
born = ask_for_date('your date of birth')
today = date.today()
extra_year = 1 if ((today.month, today.day) < (born.month, born.day)) else 0
return today.year - born.year - extra_year
print(calculate_age())
You can also use date time library in this manner. This calculates the age in years and removes the logical error that returns wrong age due to the month and day properties
Like a person born on 31 July 1999 is a 17 year old till 30 July 2017
So here's the code :
import datetime
#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))
currentDate = datetime.datetime.today().date()
#some calculations here
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day
#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)
# some decisions
if monthVeri < 0 :
age = age-1
elif dateVeri < 0 and monthVeri == 0:
age = age-1
#lets print the age now
print("Your age is {0:d}".format(age))
from datetime import datetime, date
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
return age
d=input()
year=d[0:4]
month=d[5:7]
day=d[8:]
if int(month)<=0 or int(month)>12:
print("WRONG")
elif int(day)<=0 or int(day)>31:
print("WRONG")
elif int(month)==2 and int(day)>29:
print("WRONG")
elif int(month) == 4 or int(month) == 6 or int(month) == 9 or int(month) ==11 and int(day) > 30:
print("WRONG")
else:
print(calculateAge(date(int(year),int(month),int(day))))
This code will work correctly for every date.

Is there a best way to change given number of days to years months weeks days in Python?

I am giving number of days to convert them to years, months, weeks and days, but I am taking default days to 365 and month days to 30. How do I do it in an effective way?
def get_year_month_week_day(days):
year = days / 365
days = days % 365
month = days / 30
days = days % 30
week = days / 7
day = days % 7
return year,month,week,day
def add_s(num):
if num > 1:
return 's '
return ' '
#register.filter
def daysleft(fdate):
cdate = datetime.datetime.now().date()
days = (fdate.date() - cdate).days
if days == 0:
return "Today"
elif days == 1:
return "Tomorrow"
elif days > 0:
year, month, week, day = get_year_month_week_day(days)
print year, month, week, day
days_left = ""
if year > 0:
days_left += str(year) + " year" + add_s(year)
if month > 0:
days_left += str(month) + " month" + add_s(month)
if week > 0:
days_left += str(week) + " week" + add_s(week)
if day > 0:
days_left += str(day) + " day" + add_s(day)
return days_left + " left"
else:
return "No time left"
It is much easier if you use a third-party library named python-dateutil:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.now()
>>> td = datetime.timedelta(days=500)
>>> five_hundred_days_ago = now - td
>>> print relativedelta(now, five_hundred_days_ago)
relativedelta(years=+1, months=+4, days=+13)

Why getting invalid literal when running this script?

When I run the following script, I get ValueError: invalid literal for int() with base 10: '2-' when the date only contains 1 digit (ie 02-02-2011). However it works fine when the date has 2 digits (ie 11-11-2011). What is the reason for this, and how can I fix it?
from __future__ import division
from easygui import *
import ystockquote
import datetime
import math
def main():
stock = 'NFLX'
name = ystockquote.get_company_name(stock)
start_date = create_date(02,13,2009)
end_date = create_date(10,21,2014)
start_price = get_price_on_date(stock,start_date)
end_price = get_price_on_date(stock,end_date)
if not isinstance(start_price,str):
print "Please enter a different start date, the market was closed on the day you chose!"
quit()
else:
start_price = float(start_price)
if not isinstance(end_price,str):
print "Please enter a different end date, the market was closed on the day you chose!"
quit()
else:
end_price = float(end_price)
no_of_shares = math.floor(10000/float(start_price))
profit = (end_price-start_price)*no_of_shares
print "The profit resulting from investing $10,000 in " + name + " from " + start_date + " to " + end_date + " would have been " + "$" + str(profit) + " or a return of {:.2%}".format(profit/10000) + " ."
def get_price_on_date(stock,date):
a = ystockquote.get_historical_prices(stock,date,date)
for key, value in a.iteritems() :
for key, value in value.iteritems() :
if key == 'Close':
return value
def create_date(month,day,year):
date_string = str(year) + "-" + str(month) + "-" + str(day)
return date_string
if __name__ == '__main__':
main()
Your create_date() function is not returning two-digit day and month numbers in all cases.
Try formatting the values explicitly instead of using str():
date_string = "{0:04}-{1:02}-{2:02}".format(year, month, day)

How to convert datetime [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I have this code:
from datetime import *
surname = ""
first_name = ""
birth_date = ""
nickname = ""
class Person(object):
def __init__(self, surname, first_name, birth_date, nickname=None):
self.surname = surname
self.first_name = first_name
self.birth_date = datetime.strptime(birth_date, "%Y-%m-%d").date()
self.nickname = nickname
if self.nickname is None :
self.nickname = self.surname
def get_age(self):
today = date.today()
age = today.year - self.birth_date.year
if today.month < self.birth_date.month:
age -= 1
elif today.month == self.birth_date.month and today.day < self.birth_date.day:
age -= 1
return str(age)
def get_fullname(self):
return self.surname + " " + self.first_name
petroff = Person("Petrov", "Petro", "1952-01-02")
print petroff.surname
print petroff.first_name
print petroff.nickname
print petroff.birth_date
print petroff.get_fullname()
print petroff.get_age()
print petroff.birth_date give me string "1952-01-02"
How I can change my code, to get the value of petroff.birth_date => datetime.date(1952, 1, 2)
According to datetime documentation, __str__ (which is called by print to obtain a printable view of an object) converts content of a date() to the string "1952-01-02". You can still compare date() objects as you want.

Categories

Resources