How to change the index,without giving wrong output? - python

So im trying to change the index and output the values as numbers.
this is my code:
import datetime
year = int(input('Enter the year (4 digits):\n'))
month = int(input('Enter the month (1-12)')
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,1).weekday()] + 'day'
print(date)
Sample Output:
Enter the year (4 digits):
> 2020
Enter the month (1 - 12):
> 1
Wednesday
Im trying to get the output as a index, and it should start at Sunday (Sunday = 0), but still give the correct answer. How do i go about this ?
The output i want:
Enter the year (4 digits):
> 2020
Enter the month (1 - 12):
> 1
3

There’s no reason to use DayL.
The date.weekday function already gives you the numeric weekday using Monday=0.
To map that to a Sunday=0 system, just add 1 mod 7:
weekday = (datetime.date(year,month,1).weekday() + 1) % 7

Try to use this:
>>> (datetime.datetime( 2020, 1, 1).weekday() + 1) % 7
3
>>>

Related

How can I add only months together in python?

I understand using relativedelta for exact month calculation taking into account the number of days in each month.
Are there any streamlined libraries for adding just month ints together?
ie. December is 12. Adding 2 months is 14 which is 2 == February?
I am hoping to solve all edge cases surrounding the problem with a tested library.
I have thought of doing a modulo calculation along the following:
curr_month = 12 - 1 (-1 for 0 indexing) = 11
if we do divmod(curr_month, 11) , we get (0,0) but the result in reality should be 11. If I just handled that with an if result[0] == 0: curr_month = 11, then whenever result[1] we will get the wrong answer
This formula should work for you
>>> current_month = 12
>>> delta = 2
>>> (((current_month - 1) + delta) % 12) + 1
2

Select dates in index

i have start date and end date and dataframe with daily observations. The problem is that i can't find a way, which will enable me select dates with periodicity of 3 months
for example:
2003-01-03 + 3 months = 2003-04-03 and so on
output should consist of 20 rows because 5 years with 3 months periodicity, including start and end dates
EDIT: Old solution didn't work for all cases. Therefore a new one:
start, end = returns.index[0], returns.index[-1]
length = (end.year - start.year) * 12 + (end.month - start.month)
if length % 3 == 0 and end.day >= start.day:
length += 3
new_index = []
for m in range(3, length, 3):
ydelta, month = divmod(start.month + m, 12)
day = pd.Timestamp(year=start.year + ydelta, month=month, day=1)
day += pd.Timedelta(f'{min(start.day, day.days_in_month) - 1}d')
new_index.append(day)
new_index = pd.DatetimeIndex(new_index)
returns = returns.loc[new_index]
Another version which has some slight inaccuracies around the month ends but is more compact:
add_3_months = pd.tseries.offsets.DateOffset(months=3)
new_index = pd.date_range(returns.index[0] + add_3_months,
returns.index[-1],
freq=add_3_months)
returns = returns.loc[new_index]

Making a time adding function in python

I'm trying to build a function that recieves a date and adds days, updating everything in case it changes, so far i've come up with this:
def addnewDate(date, numberOfDays):
date = date.split(":")
day = int(date[0])
month = int(date[1])
year = int(date[2])
new_days = 0
l = 0
l1 = 28
l2 = 30
l3 = 31
#l's are the accordingly days of the month
while numberOfDays > l:
numberOfDays = numberOfDays - l
if month != 12:
month += 1
else:
month = 1
year += 1
if month in [1, 3, 5, 7, 8, 10, 12]:
l = l3
elif month in [4, 6, 9, 11]:
l = l2
else:
l = l1
return str(day) + ':' + str(month) + ':' + str(year) #i'll deal
#with fact that it doesn't put the 0's in the < 10 digits later
Desired output:
addnewDate('29:12:2016', 5):
'03:01:2017'
I think the problem is with either the variables, or the position i'm using them in, kinda lost though..
Thanks in advance!
p.s I can't use python build in functions :)
Since you cannot use standard library, here's my attempt. I hope I did not forget anything.
define a table for month lengths
tweak it if leap year detected (every 4 year, but special cases)
work on zero-indexed days & months, much easier
add the number of days. If lesser that current month number of days, end, else, substract current month number of days and retry (while loop)
when last month reached, increase year
add 1 to day and month in the end
code:
def addnewDate(date, numberOfDays):
month_days = [31,28,31,30,31,30,31,31,30,31,30,31]
date = date.split(":")
day = int(date[0])-1
month = int(date[1])-1
year = int(date[2])
if year%4==0 and year%400!=0:
month_days[1]+=1
new_days = 0
#l's are the accordingly days of the month
day += numberOfDays
nb_days_month = month_days[month]
done = False # since you don't want to use break, let's create a flag
while not done:
nb_days_month = month_days[month]
if day < nb_days_month:
done = True
else:
day -= nb_days_month
month += 1
if month==12:
year += 1
month = 0
return "{:02}:{:02}:{:04}".format(day+1,month+1,year)
test (may be not exhaustive):
for i in ("28:02:2000","28:02:2004","28:02:2005","31:12:2012","03:02:2015"):
print(addnewDate(i,2))
print(addnewDate(i,31))
result:
02:03:2000
31:03:2000
01:03:2004
30:03:2004
02:03:2005
31:03:2005
02:01:2013
31:01:2013
05:02:2015
06:03:2015
of course, this is just for fun. Else use time or datetime modules!

While loops in Procedures

I am trying to output 1 to 30 days but it isn't working and it says Your code didn't display any output
here is my code:
def nextDay(year, month, day):
day = 0
while (day < 30):
day = day + 1
print day
this what they are having me do. But i am stuck on the day portion. Sorry i noticed I put month instead of day so i fixed it, but this is what I am trying to get to at the end.
Define a simple nextDay procedure, that assumes every month has 30 days.
For example:
nextDay(1999, 12, 30) => (2000, 1, 1)
nextDay(2013, 1, 30) => (2013, 2, 1)
nextDay(2012, 12, 30) => (2013, 1, 1) (even though December really has 31 days)
def nextDay(year, month, day):
"""
Returns the year, month, day of the next day.
Simple version: assume every month has 30 days.
"""
# YOUR CODE HERE
return
Well if you're trying to output 1 through 30 this will work...
for x in range(1, 31):
print 'Day: %d' % x
I literally don't get your function at all, as it makes no sense.
In addition, I don't really get why you would use a while loop for that as it is slower than both range and xrange.
Did you want this
def nextDay(year, month, day):
if day == 30:
if month == 12:
day, month = 1, 1
year+=1
else:
month+=1
else:
day+=1
return (year, month, day)
>>>nextDay(2012, 12, 30)
(2013, 1, 1)
I hope this is what you needed.
def nextDay(year, month, day):
day += 1
if day > 30:
day = 1
month += 1
if month > 12:
month = 1
year += 1
return (year, month, day)
Your code did not show anything as I don't think you have called the function.

How do I loop over the months of the year and print them in python?

year = int(input("Enter number of years: "))
total = 0
for x in range(year):
for y in range(1,13):
print("Year {0}".format(x+1))
precipitation = int(input("Enter precipitation for month {0} mm: ".format(y)))
total = total + precipitation
totalmonths = year * 12
average = total/totalmonths
print("")
Ok how do i loop it so instead of month 1 , 2 ,3 its January , February etc.
Try something like this:
import datetime
months = [datetime.date(2000, m, 1).strftime('%B') for m in range(1, 13)]
for month in months:
print month
Alternatively, something like this would also work:
import calendar
for i in range(1, 13):
print calendar.month_name[i]
Try this:
# fill a tuple with the month's names
for y in ('January', 'February', etc):
# do something
Alternatively, create a tuple whose indexes map months' numbers to names, starting at index 1 (I'm filling the first position with None because the index 0 won't be used):
months = (None, 'January', 'February', etc)
for y in range(1, 13):
m = months[y] # `m` holds the month's name
Notice that I'm using tuples and not lists because month names are unlikely to change. And although we could use a dict that maps month numbers to names, that would be overkill for this simple case.

Categories

Resources