guys, I'm doing a problem to enter a date of birth in the format dd/mm/yyyy
The instructions to follow are
Prompt the user to enter a date of birth below.
Extract the 3 fields by slicing the string into 3 slices. To separate the day from the month, you will need to first use the find() method to find the position of the first slash. To separate the month from the year, you will need to use the rfind() method to find the position of the last slash.
I've tried to do string slices and concatenation alongside indexing, but am quite shaky on how to do it, or if I'm even doing it. Were also not allowed to use conditional statements.
birthday = input("Enter your date of birth: ",)
day = birthday.find("/")
month = birthday.find("/")
year = birthday.rfind("/")
print("Day: ",day)
print("Month: ", month)
print("Year: ", year)
The format expected is:
Enter your date of birth: 30/8/1985
Day: 30
Month: 8
Year: 1985
Using rfind() is a roundabout way to do it. It will work, but you would be better off with
day, month, year = birthday.split("/")
If your instructor insists on the find/rfind approach then you can do it this way:
day = birthday[:birthday.find("/")]
month = birthday[birthday.find("/")+1:birthday.rfind("/")]
year = birthday[birthday.rfind("/")+1:]
It might be that the intention of the exercise is to teach you about slicing strings rather than how to write readable Python.
If you have further processing of date, datetime module is useful:
from datetime import datetime
birthday = input("Enter your date of birth: ")
bday = datetime.strptime(birthday, '%d/%m/%Y')
print(f'Day: {bday.day}')
print(f'Month: {bday.month}')
print(f'Year: {bday.year}')
An important advantage is that this helps prevent user from entering wrong date, for example 32 as day or 13 as month value.
Read from docs about find and rfind. They return the lowest and the highest indexes of found occurrences. So you should do instead:
b = "30/8/1985"
first_sep, last_sep = b.find("/"), b.rfind("/")
day = b[:first_sep]
month = b[first_sep+1:last_sep]
year = b[last_sep+1:]
print("Day: ", day)
print("Month: ", month)
print("Year: ", year)
Output:
Day: 30
Month: 8
Year: 1985
birthday = input("Enter your date of birth: ",)
birthday_list = birthday.split("/")
print("Day: ",birthday_list[0])
print("Month: ", birthday_list[1])
print("Year: ", birthday_list[2])
You can use regex.
birthday = input("Enter your date of birth: ",)
match = re.search(r'\d{4}-\d{2}-\d{2}', birthday)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()
Then you can get day, month, year from that.
Please refer https://docs.python.org/3/library/datetime.html#date-objects
This works spendidly:
import datetime
birthday = input('Enter your birthday in dd/mm/yyyy format')
day, month, year = list(map(int, birthday.split("/")))
birthdate = datetime.date(year, month, day)
print(f"Birthday is on {birthdate.strftime('%d/%m/%Y')}")
Related
I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string.
from datetime import datetime
today = datetime.today()
print("Please enter the date you want to find out how many days until below: ")
year = int(input("What year? "))
month = int(input("What month? "))
day = int(input("What day? "))
date2 = datetime(year, month, day)
difference = date2 - today
print(f"There are only {difference.days+1} days left until {date2} from {today}")
it prints the correct data however it shows the time aswell.
so it shows this as an example:
"There are only 96 days left until 2023-02-23 00:00:00 from 2022-11-19 00:14:18.003365"
how do I remove the time?
also if there are any other suggestions on improving this I'm all ears.
You could use date for this calculation.
from datetime import date
today = date.today()
print("Please enter the date you want to find out how many days until below: ")
year = int(input("What year? "))
month = int(input("What month? "))
day = int(input("What day? "))
date2 = date(year, month, day)
difference = date2 - today
print(f"There are only {difference.days+1} days left until {date2} from {today}")
i want to create a function in which the writes a date to his choice in dd/mm/yyyy type, and then it will print the day in the week for the wrriten date (i'm a begginer so should use simple slicing/conditions/imports (i was told as a clue to use calender.weekday).
for ex:
Enter a date: 01/01/2000
Saturday
Enter a date: 27/11/2051
Monday
Use datetime()
from datetime import datetime
day = input("Enter your date in the format dd/mm/yy")
day = datetime.strptime(day, "%d/%m/%y")
print(day.strftime('%A'))`
i am trying to write a program where I need the user to input a starting year and ending year and then the program calculates the number of days between the years. I have tried to attempt this and am a little stuck. I am required to also work out if the time includes leap years aswell.
if anyone is able to help me out would be appreciated.
The output should be as follows :
Year 1 :1980
Year 2: 2022
Number of days : 15706
import datetime
firstDate = input("Year 1?")
secondDate = input("Year 2?")
firstDateObj = datetime.datetime.strptime(firstDate, "%Y-%m-%d")
secondDateObj = datetime.datetime.strptime(secondDate, "%Y-%m-%d")
totalDays = (firstDateObj – secondDateObj).days
print(totalDays, "Day(s)")
except ValueError as e:
print(e)
thanks
Try using the datetime.date method:
Using this method you can just take the first of January of each year:
from datetime import date
first_year = input("Year 1? ")
second_year = input("Year 2? ")
first_date = date(int(first_year), 1, 1)
second_date = date(int(second_year), 1, 1)
Subtracting these elements returns a datetime.timedelta object -
between_days = second_date - first_date
print(between_days.days)
I tried doing it the long way by simply going down the months one by one but my teacher told me the long was was unacceptable. Now I have the day and month printed but am not sure how to quickly change the number given into the month it represents. This is what I have so far.
birthMonth = int(input("Enter your Birth Month:"))
if birthMonth <= 0 or birthMonth > 12:
print("Invalid, Choose again")
else:
birthDay = int(input("What day?:"))
if birthDay <=0 or birthDay > 31:
print('Not a valid Birthday')
else:
print(birthMonth, birthDay)
It will print the number and the day which is fine but she does not want me to list out all of the months. I would appreciate any help I can get.
You can use the datetime module to get the month associated with a number.
>>> import datetime
>>> month_num = 8
>>> month = datetime.date(2017, month_num, 1).strftime("%B")
>>> print(month)
August
Another alternative (probably the better one) is to use the calendar module
>>> import calendar
>>> month_num = 8
>>> calendar.month_name[month_num]
August
So, in your code, you can replace
print(birthMonth, birthDay)
with
print(calendar.month_name[birthMonth], birthDay)
but, make sure that you import the calendar module.
I need to write a function that that takes four arguments: day, month, and year as numbers. Weeks must be one of the following: MTWRFSU and converts this date into a human-readable string.
The output should look like:
Enter day: 28
Enter month: 9
Enter Year: 2014
Enter weekday: U
Date is: Sunday, September 28,2014.
So far my code looks like this and I am pretty stumped can anyone help an average programmer out?:
#FUNCTION THAT TAKES 4 ARGUMENTS.
day = int(input('Enter day: '))
month = int(input('Enter month: '))
year = int(input('Enter year:'))
weekday = str(input('Enter weekday: ')) #MTWRFSU
def total():
day = int(input('Enter day: '))
if day >= 32:
month = int(input('Enter month: '))
else:
print('Please enter a valid day for a month. Numbers 1 through 31.')
if month >= 12:
year = int(input('Enter Year: '))
else:
print('Please enter a valid month: ')
total()
import datetime
def total(day, month, year):
date = datetime.date(year, month, day)
return '{0:%A}, {0:%B} {0:%d}, {0:%Y}'.format(date)
day = int(raw_input("Please enter the day (1-31)"))
month = int(raw_input("Please enter the month (1-12)"))
year = int(raw_input("Please enter the year"))
print total(day, month, year)
This uses python's datetime module to handle dates. The return line uses string formatting, where {0:?} refers to the first (only) thing inside of .format() and then formats it appropriately (for month, day and year)
Also, don't use input in python 2.x (if this is python 3.x then go ahead)
You might notice that I only use 3 inputs - that's because datetime can figure out the day of the week without being told. This can be trivially changed to ask for that as well, however.