Generating a date in a particular format using python - python-3.x

I have a python code that looks like this. I am receiving the values
of year, month and day in form of a string. I will test whether they are not null.
If they are not null I will like to generate a date in this format MMddyyyy from the variables
from datetime import datetime
year = "2022"
month = "7"
day = "15"
if len(year) and len(month) and len(day):
print('variables are not empty')
#prepare = "{month}/{day}/{year}"
#valueDt = datetime.strptime(prepare,"%m/%d/%Y")
else:
print('variables are empty')
The solution I have is not working. How can I generate this date?

It should work without calling len as well.
from datetime import datetime, date
year = "2022"
month = "7"
day = "15"
if year and month and day:
print('variables are not empty')
prepare = date(int(year), int(month), int(day))
valueDt = datetime.strftime(prepare, "%m/%d/%Y")
print(valueDt)
else:
print('variables are empty')

from datetime import datetime, date
year = "2022"
month = "7"
day = "15"
if len(year) and len(month) and len(day):
print('variables are not empty')
prepare = date(int(year), int(month), int(day))
valueDt = datetime.strftime(prepare, "%m/%d/%Y")
print(valueDt)
else:
print('variables are empty')

Related

How to make a datetime object from user input?

I am trying to make an alarm clock. How to make a datetime object from user-input, where the user-input is hours, minutes, and secs seperately. For example:
from datetime import datetime
# user-input: at 2:30
hr = "2"
m = "30"
s = "0"
from datetime import datetime
def GetDate():
isValid=False
while not isValid:
userIn = input("Type Date dd/mm/yy: ")
try: # strptime throws an exception if the input doesn't match the pattern
d = datetime.datetime.strptime(userIn, "%d/%m/%y")
isValid=True
except:
print("Invalid")
return d
#test the function
print(GetDate())

How do I loop through days in months in python3?

Say for the year of 2020, how do I iterate through the days in the months so that my outcome would be in the following format:
Jan1
Jan2
Jan3
....
Jan31
Feb1
I've tried so many things online but I couldnt find an answer. Please help :(
Both of these methods will handle leap years correctly out of the box.
Using a simple while loop:
from datetime import datetime, timedelta
def iter_days(year):
dt = datetime(year, 1, 1)
while dt.year == year:
yield dt
dt += timedelta(days=1)
Using date rules:
from datetime import datetime
from dateutil.rrule import rrule, DAILY
def iter_days(year):
first_date = datetime(year, 1, 1)
last_date = datetime(year, 12, 31)
return rrule(DAILY, dtstart=first_date, until=last_date)
Both would be used the same:
for dt in iter_days(2020):
print(dt.strftime('%b%-d'))
The format string '%b%-d' will give you the format you specified in your question. I don't know if that was a requirement or not.
This is crude but gets what you want for 2020. You'll need to change 366 to 365 for non-leap-years.
#!/usr/bin/python3
import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
print(dayOfYear.strftime('%b %d, %Y'))
The calendar module offers quite a bit of functionality.
Here is a solution that works for any given year
import calendar as cal
for mi in range(1,13):
_, days = cal.monthrange(2020, mi)
for d in range(1, days+1):
print(cal.month_name[mi], d)

How do i use a list of holidays like this to find holidays in my day's list. this method gives me an error

import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
holidays=[2020-1-5, 2020-1-11, 2020-1-13]
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
if dayNum in holidays:
print("HOLIDAY")
Something like this should work
from datetime import datetime, timedelta
startDate = '2020-01-01'
start = datetime.strptime(startDate, '%Y-%m-%d')
holidays_str = ['2020-01-05', '2020-01-11', '2020-01-13']
holidays = [datetime.strptime(day, '%Y-%m-%d') for day in holidays_str]
for day in range(0, 366):
day_of_year = start + timedelta(days=day)
if day_of_year in holidays:
print(datetime.strftime(day_of_year, '%Y-%m-%d'), "HOLIDAY")
import datetime
startDate = '2020-01-01'
start = datetime.datetime.strptime(startDate, '%Y-%m-%d')
holidays=["2020-01-01", "2020-01-03", "2020-01-05"]
for dayNum in range(0,366):
dayOfYear = start + datetime.timedelta(days=dayNum)
if str(dayOfYear).split(" ")[0] in holidays:
print(str(dayOfYear).split(" ")[0]+" is HOLIDAY")
try this

Python Best Syntactic way of Calculating the age based on datetime

After searching around the web got the below two ways to get the age of a person.
Just curious to Know if there is better synthetic way of calculating & writing it in 3.x version of python.
First way around ...
$ cat birth1.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
import datetime
year = datetime.datetime.now().year # getting current year from the system
year_of_birth = int(input("Enter Your Birth Year: "))
print("You are %i Year Old" % (year - year_of_birth))
The Result produced..
$ ./birth1.py
Enter Your Birth Year: 1981
You are 37 Year Old
Second way around ....
$ cat birth2.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
from datetime import datetime, date
print("Your date of birth (dd/mm/yyyy)")
date_of_birth = datetime.strptime(input("Please Put your age here: "), "%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("You are %i Year Old." % (age))
The Result produces..
$ ./birth2.py
Your date of birth (dd/mm/yyyy)
Please Put your age here: 22/09/2015
You are 2 Year Old.
Take advantage of timedelta.
import datetime as dt
def years_ago(start: str):
sec_per_year = 365.24 * 24 * 60 * 60
delta = dt.datetime.now() - dt.datetime.strptime(start, '%d/%m/%Y')
return delta.total_seconds() / sec_per_year
if __name__ == '__main__':
print(int(years_ago(input('What is your date of birth (dd/mm/yyyy) ? '))))

Convert dates to specific format

I have a pandas dataframe that looks like:
import pandas as pd
df1 = pd.DataFrame({'Counterparty':['Bank','Client','Bank','Bank','Bank','Bank'],
'Date':['4Q18','1Q19','2Q19','4Q21','FY22','H123']
})
I want to convert the 'Date' column from a string to a date such that the date is the last date for that particular period. ie 'FQ18'= 31st Dec 2018, '1Q19' = 31st Mar 2019, 'FY22' = 31st Dec 2022,'H123'= 30th June 2023
Any suggestions how to achieve this ?
As mentioned by #jpp, you're going to have to do some customization. There isn't existing functionality to map "FY22" to 2022-12-31, to my knowledge. Here's something to get you started, based on the limited example you've shown:
import re
import pandas as pd
from pandas.core.tools.datetimes import DateParseError
from pandas.tseries import offsets
halfyr = re.compile(r'H(?P<half>\d)(?P<year>\d{2})')
fiscalyr = re.compile(r'FY(?P<year>\d{2})')
def try_qend(date):
try:
return pd.to_datetime(date) + offsets.QuarterEnd()
except (DateParseError, ValueError):
halfyr_match = halfyr.match(date)
if halfyr_match:
half, year = [int(i) for i in halfyr_match.groups()]
month = 6 if half == 1 else 12
return pd.datetime(2000 + year, month, 1) + offsets.MonthEnd()
else:
fiscalyr_match = fiscalyr.match(date)
if fiscalyr_match:
year = int(fiscalyr_match.group('year'))
return pd.datetime(2000 + year, 12, 31)
else:
# You're SOL
return pd.NaT
def parse_dates(dates):
return pd.to_datetime([try_qend(date) for date in dates])
Assumptions:
All years are 20yy, not 19xx.
The regex patterns here completely describe the year-half/fiscal-year syntax set.
Example:
dates = ['4Q18','1Q19','2Q19','4Q21','FY22','H123']
parse_dates(dates)
DatetimeIndex(['2018-12-31', '2019-03-31', '2019-06-30', '2021-12-31',
'2022-12-31', '2023-06-30'],
dtype='datetime64[ns]', freq=None)

Resources