Function to get year , month and day from a given age in python - python-3.x

Need a function to get DOB from a given age, so if age = 60 .. output will be in format %m,%d,%Y => '08/16/1962' .. assuming current date from date.today() is 2022-08-16 .. need to change format to be 08-16-2022

Try it like this:
age = int(input)
today = date.today()
todayFormat = today.strftime('%m/%d/%Y')
return todayFormat.replace(year = todayFormat.year - age)
I assumed age is a consoleinput,
date.today creates the current date as date object,
date. replace replaces certain parts of a date.

Related

Get dynamic dates for URL on any day of the month

I'm scraping a website with requests. The URL requires dynamic dates so i'm generating the dates to use with the following variables:
stmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthBegin(-1)).strftime('%d-%b-%Y')
todDt = (pd.to_datetime('today').date()).strftime('%d-%b-%Y')
snmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthBegin(1)).strftime('%d-%b-%Y')
enmDt = (pd.to_datetime('today').date()+ pd.offsets.MonthEnd(2)).strftime('%d-%b-%Y')
For this example, i'm running this script on 11/30/2022 (last day of the month).
stmDt = start this month date (first day of month on which we run script - 11/1/2022)
todDt = today (11/30/2022)
snmDt = start next month (12/1/2022)
enmDt = end next month (12/31/2022)
The date variables are correct most of the time, but it appears (for november run dates):
On the first day of the month: stmDt shows the first day of the
previous month (10/1/22)
On the last day of the month: enmDt shows the last day two months
from now (1/31/23)
How can I tweak these so they always give me the correct dates? Happy to use other packages to accomplish etc
Thanks
You can do this using dateutil.relativedelta like this:
from datetime import datetime
from dateutil.relativedelta import relativedelta
today = datetime.now()
stmDt = today.replace(day=1).strftime('%d-%b-%Y')
todDt = today.strftime('%d-%b-%Y')
snmDt = (today + relativedelta(months=1)).replace(day=1).strftime('%d-%b-%Y')
enmDt = ((today + relativedelta(months=2)).replace(day=1) - relativedelta(days=1)).strftime('%d-%b-%Y')

How to find day of the week for each date of that month if the day of first date is given?

I need to find the day of each other day of a month if the first day is Friday of that month. Need to write a function named returnDay which will take one parameter that is the date of that month. The date should be in range of 1 and 31. When I input a date of the month, then have to call that function which returns it's day. If the actual parameter is less than 1 or greater than 31, give a hint that the input isn't available date of that month.
So my question is how to put the 1-31 range here and what is the issue that it shows name 'date' is not defined whenever I run this?
def returnDay(date):
day_names= ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
day= input("Enter first day of the month: ")
date = int(input('please enter the date of October: '))
i = date%7 -1
if day in day_names:
j = day_names.index(day)+i
if j >= 7:
j = j - 7
return(day_names[j])
print(returnDay(date))
I see a couple of problems in your code. From the way you are calling returnDay(date), it looks like you want to have the date as a parameter to this function. You cannot retrieve the date as input from the user, from within the same function that also needs the date as an argument. So first rewrite your code so that you set the input from outside this function scope, and then supply it to your function for processing. The same goes for the integer part of your date. Now for the logic behind calculating the day to return:
A user supplies the first day
A user supplies the current date
let's go
def returnDay(firstDay,currentDate):
days_in_week = ['Monday','Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday']
day_offset = 0
for i in range(7):
if firstDay == days_in_week[i]:
day_offset += i
index_days_in_week = (currentDate + day_offset)%7 - 1
return days_in_week[index_days_in_week]
def main():
firstDay = input("supply the first day of the month")
currentDate = input("supply current day of the month")
returnDay(firstDay, currentDate)
main()
You may need to optimise it in order to work completely. I leave this as a homework assessment to you.

Invalid Dates Python

I am new to Python. I was just wondering, how can you write code that makes beyond a certain date an invalid input. For example, if the user inputs anything after 12/02/2013, it will produce an error. Everything after that date will work perfectly
As glibdud suggested, use datetime objects.
date = datetime.date(YYYY, MM, DD)
where (YYYY, MM, DD) are integers representing years, months, and days. The condition can then be checked in your script with
inputDate > maxDate
for example:
import datetime
maxDate = datetime.date(2013, 12, 2)
y = int(input('Enter year:'))
m = int(input('Enter numerical month (1-12):'))
d = int(input('Enter numerical day (1-31):'))
inputDate = datetime.date(y, m, d)
if inputDate > maxDate:
print('Error - date after 02 December 2013')
else:
print('Success!')
Gives:
Enter year:2018
Enter numerical month (1-12):1
Enter numerical day (1-31):1
Error - date after 02 December 2013
and
Enter year:2000
Enter numerical month (1-12):1
Enter numerical day (1-31):1
Success!

Python date range based on current date

I'm looking to achieve a search of files based on user input on a date. For example, I'm attempting to write the script to ask user for a range in which to search (month to date, last full week, or specific day).
last full week needs to go backward, to the last full week - so if today is Wednesday, the script should go back to the previous (2)Sunday(s) as a start range to the Saturday that just past, while also accounting for what day it is currently:
Sun(start)---Mon---Tue---Wed---Thu---Fri---Sat(end)---Sun---Mon---Tue---Wed (today)
Howevver, it needs to also account for what day it is in relation to the above, meaning that regardless of what "today" is, the search criteria is always one full week behind (if its Sunday, it just goes to last sunday to 'yesterday, Saturday')
From some examples attempting similar things I've seen here and here, I've attempted to join, modify, and add over the last couple of days:
import datetime
import os
import dateutil.relativedelta
import timedelta
class AuditFileCheck():
"""File Compliance Checker."""
def datechoice(self):
"""Select date."""
print("Checking the Audit Files for compliance.")
print("Today is", datetime.date.today().strftime(" %A."))
print("\nI will check either for file compliances."
"\nSearch criteria is either by MONTH to date, last full WEEK, "
"or individual DAY: [M/W/D]")
print(now.strftime('Week of %Y%m%d'))
weekbefore = now - timedelta(days=6)
print(
"Week of {weekbefore:%A, %m-%d-%Y} to {now:%A, %m-%d-%Y}").format(**vars())
input_search = input(
"Enter search range: Month to date, Prior Week, or by day [M/W/D]")
def search_month(d, w, m, weekday, month):
"""Establish search from month start, or prior month if today is first of current month."""
if input_search.lower() == "m":
current_month = datetime(today.month, 1, today.year)
if current_month == datetime.today():
current_month == dateutil.relativedelta.relativedelta(
months=-1)
return m - datetime.timedelta(current_month)
m = current_month()
print(current_month)
# TODO ensure the prior month is used if 'today' is before the end of
# first full week in current month
if input_search.lower() == "w":
prior_week = weekday + d.weekday()
if prior_week >= 0: # Target day already happened this week
prior_week -= 6
return d - datetime.timedelta(prior_week)
d = datetime.date.today()
# 6 = Sunday, 0 = Monday, 1 = Tuesday...
previous_monday = previous_weekday(d, 6)
print(previous_monday)
# TODO search files
if input_search.lower() == "d":
day_search = input(
"Enter a specific date within to search [YYYYMMDD]")
return d
print("Searching through...")
# TODO search files from set_day
This bit:
previous_sunday = previous_weekday(d, 8)
adjusting the integer adjusts how far back it looks.
I'm having some trouble with getting this to function properly. What am I doing wrong here? The more I attempt to play with it, the more confused I become and less it works...

taking date input and grouping pandas datfarme as per time

I have a pandas dataframe with date and time values as follows.
Date Time Pattern
0 06/01/13 0:00:01 A
1 06/02/13 1:00:01 B
2 06/03/13 2:00:01 A
3 06/04/13 3:00:01 C
Now i intend to take date input from user as follows:
date = str(input('Input date in mm-dd-yy format'))
Now how should i find/group by all the rows with input date by user and copy it to a new dataframe. I tried many things but got confused with datatime conversion.
How should i go about it?
First make sure your Date column is datetime
df.Date = pd.to_datetime(df.Date)
Then use query
date = pd.to_datetime(input('Input date in mm-dd-yyyy format'))
df.query('Date == #date')
response to #learningprogramming
You can include other criteria in query
date = pd.to_datetime(input('Input date in mm-dd-yyyy format: '))
df.query('Date == #date & Pattern == "B"')
loc works as well
date = pd.to_datetime(input('Input date in mm-dd-yyyy format: '))
df.loc[(df.Date == date) & (df.Pattern == 'B')]
putting all in the inputs
date = pd.to_datetime(input('Input date in mm-dd-yyyy format: '))
pattern = str(input('Input pattern type: '))
df.query('Date == #date & Pattern == #pattern')
Is the column named 'Date' a string? If so, you can try something like:
subset = df[df['Date'] == date]

Resources