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'))`
Related
Is there a way to use Python to get last Friday's date and store it in a variable, regardless of which day of the week the program runs?
That is, if I run the program on Monday June 19th 2021 or Thursday June 22nd 2021, it always returns the previus Friday as a date variable: 2021-07-16.
To get the day of the week as an int we use datetime.datetime.today().weekday() and to subtract days from a datetime we use datetime.today() - timedelta(days=days_to_subtract) now we can make a dictionary linking the day of the week to the number of days to subtract and use that dictionary to make a subtraction:
from datetime import datetime, timedelta
d = {0:3,1:4,2:5,3:6,4:0,5:1,6:2}
lastfriday = datetime.today()-timedelta(days=d[datetime.today().weekday()])
Your question is similar to this one
Here's a starting point:
import datetime
def get_last_friday():
current_time = datetime.datetime.now()
last_friday = (current_time.date()
- datetime.timedelta(days=current_time.weekday())
+ datetime.timedelta(days=4, weeks=-1))
return last_friday
I just want to write a script for taking the date
as input from user, if user don't enter date then program should take system's date.
I tried the following code. How can I do this by using any if-else condition or any functions in Python.
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)
How can I write this script for above problem?
It's best to use exception handling for this matter.
Use try and except to handle any exceptions thrown by datetime module whenever any input given is not according to the format wanted.
try:
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)
except ValueError:
date1=datetime.date.today().strftime('%Y-%m-%d')
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')}")
So I'm trying to subtract one day from a users input of 2018-02-22 for example. Im a little bit stuck with line 5 - my friend who is is leaps and bounds ahead of me suggested I try this method for subtracting one day.
In my online lessons I haven't quite got to datetime yet so Im trying to ghetto it together by reading posts online but got a stuck with the error :
TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date()
new = date1.replace(day=date1.day-1, hour=1, minute=0, second=0, microsecond=0)
print (new)
So my aim is the get the out put 2018-02-21 if I put in 2018-02-22.
Any help would be amazing :)
First of all a timedeltais best used for the purpose of doing date arithmetcs. You import timedelta but don't use it.
day = timedelta(days=1)
newdate = input_datetime - day
Second problem is you're not initializing a date object properly. But in this case it would be better to use datetime as well as strptime to parse the datetime from the input string in a certain format.
date_entry = input('Enter a date in YYYY-MM-DD format')
input_date = datetime.strptime(date_entry, "%Y-%m-%d")
day = timedelta(days=1)
newdate = input_datetime - day
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
date1 = datetime.strptime(date_entry, '%Y-%m-%d')
print date1+timedelta(1)
Maybe you need something like this
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format ')
# convert date into datetime object
date1 = datetime.strptime(date_entry, "%Y-%m-%d")
new_date = date1 -timedelta(days=1) # subtract 1 day from date
# convert date into original string like format
new_date = datetime.strftime(new_date, "%Y-%m-%d")
print(new_date)
Output:
Enter a date in YYYY-MM-DD format 2017-01-01
'2016-12-31'
I must have the user enter a date in mm/dd/yy format and then output the string in long-date format like January, ##, ####. I cannot for the life of me get the month to replace as a the word.
def main():
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
validate(month, day, year)#validates input
get_month(get_date)
def validate(month,day,year):
while month>12 or month<1 or day>31 or day<1 or year!=15:
print("if you would like to enter a one-digit number, enter a zero first, then the number\n theres only 12 months in a year\n only up to 31 days in a month, and\n you must enter 15 as the year")
get_date=input('Input a date in mm/dd/yy format!:')
month= int(get_date[:2])
day=int(get_date[3:5])
year=int(get_date[6:])
def get_month(get_date):
if get_date.startswith('01'):
get_date.replace('01','January')
print(get_date)
I have tried a plethora of things to fix this but I cannot make January appear instead of 01.
Strings in Python are immutable, they don't change once they're created. That means any function that modifies it must return a new string. You need to capture that new value.
get_date = get_date.replace('01','January')
You can do this (and simplify the code) using python's date module.
The strptime function will parse a date from a string using format codes. If it's can't parse it correctly, it will raise a value error, so no need for your custom validation function
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strptime
The strftime function will print out that date formatted according to the same codes.
https://docs.python.org/2.7/library/datetime.html#datetime.datetime.strftime
Updated, your code would look something like this:
from datetime import datetime
parsed = None
while not parsed:
get_date=input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
try:
parsed = datetime.strptime(get_date, '%m/%d/%y')
except ValueError:
parsed = None
print parsed.strftime('%B %d, %Y')
Why don't you use datetime module ?
year = 2007; month=11; day=3
import datetime
d = datetime.date(year, month, day)
print d.strftime("%d %B %Y")
You might be better off using Python's datetime module for this:
from datetime import datetime
entered_date = input('Input a date in mm/dd/yy format!\nIf you would like to enter a 1-digit number, enter a zero first, then the number\nDate:')
d = datetime.strptime(entered_date, '%m/%d/%y')
entered_date = d.strftime('%B, %d, %Y')
e.g.
'February, 29, 2016'
This way you catch invalid dates (such as 02/29/15) as well as badly-formatted ones.