extract last day and first day from month in python - python-3.x

i am new in python ,i have a string of this format
Ex. 'Mar-00'
how could i calculate first day and last day from this month.
OUTPUT :
first day : 01-Mar-00
last day : 31-Mar-00
ex : 'Feb-17'
first day : 01-Feb-17
last day : 28-Feb-17

you can use calendar.monthrange(year, month)[1] to get the number of days in a given month+year.
the first is alway 01, and last is the value of calendar.monthrange(year, month)[1]
try this, let me know if it works:
import calendar
month_abbr_to_num = {v: k for k,v in enumerate(calendar.month_abbr)}
month_abbr, year_2_digit = input("please enter month, e.g. Mar-00: ").split('-')
month = month_abbr_to_num[month_abbr]
year = int('20'+year_2_digit)
days_in_month = calendar.monthrange(year,month)[1]
print("first day : {:02d}-{}-{}".format(1, month_abbr, year_2_digit))
print("last day : {:02d}-{}-{}".format(days_in_month, month_abbr, year_2_digit))
EDIT:
following your comment on original question, here it is in the form of a function that returns both as datetime objects:
import calendar
import datetime
month_abbr_to_num = {v: k for k,v in enumerate(calendar.month_abbr)}
def get_first_and_last_day(user_input):
month_abbr, year_2_digit = user_input.split('-')
month = month_abbr_to_num[month_abbr]
year = int('20' + year_2_digit)
days_in_month = calendar.monthrange(year, month)[1]
first_day = datetime.datetime(year, month, 1)
last_day = datetime.datetime(year, month, days_in_month)
return first_day, last_day
first, last = get_first_and_last_day(input("please enter month, e.g. Mar-00: "))
print("first day : ",first)
print("last day : ",last)

Related

one function used to change variable in another function

# making a basic calendar
#list of months and their days
month_day = [[1,'January',31],[2,'February',28],
[3,'March',31],[4,'April',30],
[5,'May',31],[6,'June',30],
[7,'July',31],[8,'August',31],
[9,'September',30],[10,'October',31],
[11,'November',30],[12,'December',31]]
#checksum for new year
def isleapyear(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
month_day[1][2] = 29
else:
month_day[1][2] = 28
else :
month_day[1][2] = 29
else:
month_day[1][2] = 28
#editable date (supposed to be
def Date():
year = 1
day = 31
month = 1
isleapyear(year)
date = [day, month_day[month-1][1], year]
return date
#function to increase day counter by 1
def new_day():
#checksum for month or year rollover
if Date.day == month_day[Date.month-1][2]:
Date.day = 1
if Date.month == 12:
Date.month = 1
Date.year = Date.year + 1
else:
Date.month = month + 1
else:
Date.day = Date.day + 1
new_day()
print (Date())
I am trying to teach myself python, so I have made a project a few smaller projects working together and one of them is a Date tracker. The Date function works. however when i try to call the new day function to bump the day by 1 and change month and year if needed, i get an error "AttributeError: 'function' object has no attribute 'day'". I understand that inside a function is a separate local variable not a global and that your not supposed to make global variables constantly changing. So I'm trying to get one function to call and use anothers variable I plan on making it into a button that changes the day by 1 or 7, I'm just having trouble visualizing how to get the function working. Any direction or help with getting this to work would be greatly appreciated
Thank you all in advance!
Firstly, you can't get variables from function.
One way you can deal with it is in function Date add line global year, day, month, this will make variables year, day, month global so you can use it in all function and outside of functions. And in new_day remove Date..
This should get rid of your problem.
Date.day would only work if Date was class not function.
For example:
class Date:
def __init__(self):
self.year = 1
self.day = 31
self.month = 1
Date().year # Should return 1
Date().day # Should return 31
Date().month # Should return 1

How to merge 2 sublists in a list of time intervals if the times are successive?

Given this calender of interval times when a person in booked :
list = [['10:00','11:30'],['12:30','14:30'],['14:30','15:00'],['16:00','17:00'],['17:30','20:00'],['20:00','21:00']]
example : The person is booked from 10:00 to 11:30,and is free from 11:30 to 12:30.
ps : Every sublist is an Appointment.
i would like to make a python script that can arrange the list to look like this :
output =[['10:00','11:30'],['12:30','15:00'],['16:00','17:00'],['17:30','21:00']]
where we merge the successive appointments when the end Time of the first is equal to the end Time of the second.
Try this:
list = [['10:00','11:30'],['12:30','14:30'],['14:30','15:00'],['16:00','17:00'],['17:30','20:00'],['20:00','21:00']]
merged = []
for appt in list:
if len(merged) == 0:
merged.append(appt)
else:
last = merged[-1]
if appt[0] == last[1]:
last[1] = appt[1]
else:
merged.append(appt)
print(merged)
Gives:
[['10:00', '11:30'], ['12:30', '15:00'], ['16:00', '17:00'], ['17:30', '21:00']]

Duration Calculator in Python

I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'

Output formate for calendar in Python 3.6

I would like to format the output in terms of calendar format. I have tried with print statement, but could not achieve as I expected because rows and column is not aligned properly.Could anyone help me to format and align the output? Here I have shared my entire code which is written in Python 3.6. the same question I have asked before but could not get any reply. but this code is little better than my previous code.
import calendar
import datetime
tamil_day = ('Monday','Tuesday','Wednesday','Thusday','Friday','Saturday','Sunday')
tamil_month = ('Chithirai','Vaikasi','Aani','Aadi','Aavani','Puratasi','Ipasi','Karthikai','Maargali','Thai','Masi','Panguni')
'''SAKA year Each month starting day in AD year 1st position for common year and 0th position for leap year'''
saka_month_starting_day_in_ad = (21,22,21,22,22,23,23,23,23,22,22,21,20)
'''equal month in AD year for SAKA month starting'''
ad_month = (3,3,4,5,6,7,8,9,10,11,12,1,2)
''' number of days in each month in SAKA year. add one ine more day each month for calculation'''
no_days_in_saka_month = (31,30,31,31,31,31,31,30,30,30,30,30,30)
def saka_month(saka_year,month):
ad_year = saka_year+78
saka_month = []
temp = 0
if month == 1 and calendar.isleap(ad_year):
first_day = datetime.date(ad_year,ad_month[month],saka_month_starting_day_in_ad[month-1]).weekday()
else:
first_day = datetime.date(ad_year,ad_month[month],saka_month_starting_day_in_ad[month]).weekday()
while first_day != temp:
saka_month.append(str(' '))
temp+=1
for day in range(1,(no_days_in_saka_month[month]+1)):
saka_month.append(str(day))
if day == no_days_in_saka_month[month] and calendar.isleap(ad_year):
saka_month.append(str(day+1))
for i in range(0,42,7):
print(*saka_month[i:i+7],sep=' ',end='\n')
print('\n')
def saka_year_print(saka_year):
for month in range(0,12):
print('{:*^80}'.format(tamil_month[month]))
print('\n')
print(*tamil_day,sep=' ')
print('\n','\n','\n')
saka_month(saka_year,month)
i have found the solution to my problem. just add str.center() for every list element. in my code at line no.47,50 and 52 you can add the center() function so that we can get aligned matrix kind of calendar in month view.
thank you

The .apply() method is not working

So friends is a column with a list in each instance such as df['friends][0] = [id1, id2, ..., idn]. I'm trying to count the number of friends in a separate column such as df['friend_counts'][0] = n.
I did the following. I've used this code in other datasets, but for some reason it's taking forever and the dataset is only 300,000 instances.
df_user['friend_counts'] = df_user['friends'].apply(lambda x: len(df_user.friends[x]))
Also, for some reason this following code creates a season column but is not populated, i.e. it's all just blank spaces. This is troublesome since I did this exact same code for every other dataset. Did they change the .apply() method?
#Convert 'date' to a date time object
df_reviews["date"] = pd.to_datetime(df_reviews["date"])
#Splitting up 'release_date' -> 'release_weekday', 'release_month',
'release_year'
df_reviews["weekday"] = df_reviews["date"].dt.weekday_name
df_reviews["month"] = df_reviews["date"].dt.month
df_reviews["year"] = df_reviews["date"].dt.year
### Helper function
def season_converter(month_name):
""" Returns the season a particular month is in """
season = ""`enter code here`
#Winter
if month_name in ['Jan', 'Feb', 'Dec']:
season = "Winter"
#Spring
if month_name in ['Mar', 'Apr', 'May']:
season = "Spring"
#Summer
if month_name in ['Jun', 'Jul', 'Aug'] :
season = "Summer"
#Fall
if month_name in ['Sep', 'Oct', 'Nov']:
season = "Fall"
#Other
if month_name == "NA":
season = "NA"
return season
#Create a new column that holds seasonal information
df_reviews['season'] = df_reviews['month'].apply(lambda x:
season_converter(x))
I suggest use map by dictionary for improve performance:
d = {1:'Winter', 2:'Winter', 12:'Winter', 3: 'Spring', .... np.nan:'NA', 'NA':'NA'}
df_reviews['season'] = df_reviews['month'].map(d)
Another solution if is possible use numeric seasons:
df_reviews['season'] = (df_reviews['month'] % 12 + 3) // 3

Resources