Python date function bugs - python

I am trying to create a function in python which will display the date. So I can see the program run, I have set one day to five seconds, so every five seconds it will become the next 'day' and it will print the date.
I know there is already an in-build function for displaying a date, however I am very new to python and I am trying to improve my skills (so excuse my poor coding.)
I have set the starting date to the first of January, 2000.
Here is my code:
import time
def showDate():
year = 00
month = 1
day = 1
oneDay = 5
longMonths = [1, 3, 5, 7, 8, 10, 12]
shortMonths = [4, 6, 9, 11]
while True:
time.sleep(1)
oneDay = oneDay - 1
if oneDay == 0:
if month in longMonths:
if day > 31:
day = day + 1
else:
month = month + 1
day = 0
if month == 2:
if day > 28:
day = day + 1
else:
month = month + 1
day = 0
if month in shortMonths:
if day > 30:
day = day + 1
else:
month = month + 1
day = 0
if day == 31 and month == 12:
year = year + 1
print(str(day) + '/' + str(month) + '/' + str(year))
oneDay = 5
showDate()
However, when I try to run the program this is the output I get this:
>>>
0/3/0
0/5/0
0/7/0
0/8/0
0/10/0
0/12/0
0/13/0
0/13/0
0/13/0
I don't know why this is happening, could someone please suggest a solution?

There's no possible path through your code where day gets incremented.
I think you are actually confused between > and <: you check if day is greater than 31 or 28, which it never is. I think you mean if day < 31: and so on.

First of all, it's easier to just set time.sleep(5) instead of looping over time.sleep(1) 5 times. It's better to have a list of values with days of the month, not just 2 lists of the long and short months. Also your while loop is currently indefinite, is that intentional?
Anyway, your main problem was comparing day > 31, but there's lots of things that can be improved. As I said, I'm removing the use of oneDay to just do sleep(5) as it's cleaner and having one daysInMonths list.
import time
def showDate():
year = 00
month = 1
day = 1
daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Now you can have only one if check about if the day has reached the end of a month, like this:
while True:
time.sleep(5)
if day < daysInMonths[month-1]:
day += 1
This will check the index of the list for the current month. It uses -1 because lists begin at index 0, and your months begin at 1. (ie. the months run from 1-12 but the list's indices are 0-11). Also I used the += operator, which is basically short hand for var = var + something. It works the same and looks neater.
This test encompasses all months, and then the alternative scenario is that you need to increment the month. I recommend in this block that you first check if the month is 12 and then increment the year from there. Also you should be setting day and month back to 1, since that was their starting value. If it's not the end of the year, increment the month and set day back to 1.
else:
if month == 12:
year += 1
day = 1
month = 1
else:
month += 1
day = 1
print("{}/{}/{}".format(day, month, year))
I also used the string.format syntax for neatness. With format, it will substitute the variables you pass in for {} in the string. It makes it easier to lay out how the string should actually look, and it converts the variables to string format implicitly.

Try this.
The day comparisons should be <, not >. When going to the next month, I set the day to 1, because there are no days 0 in the calendar. And I use elif for the subsequent month tests, because all the cases are exclusive.
def showDate():
year = 00
month = 1
day = 1
oneDay = 5
longMonths = [1, 3, 5, 7, 8, 10, 12]
shortMonths = [4, 6, 9, 11]
while True:
time.sleep(1)
oneDay = oneDay - 1
if oneDay == 0:
if month in longMonths:
if day < 31:
day = day + 1
else:
month = month + 1
day = 1
elif month == 2:
if day < 28:
day = day + 1
else:
month = month + 1
day = 1
if month in shortMonths:
if day < 30:
day = day + 1
else:
month = month + 1
day = 1
if day == 31 and month == 12:
year = year + 1
month = 1
print(str(day) + '/' + str(month) + '/' + str(year))
oneDay = 5

Related

print the first three months as a string in python

day = 1
month = 3
for x in range(3):
while day <= 31:
print(str(month)+"/"+str(day)+"/2019'")
day += 1
month += 1
I am trying to print the first 31 days from March-May. (I know April has 30 days, but I am not concerned with that.
The while loop works, printing out the first 31 days in march. The code does not loop through 2 more times and increment the month to sequentially print out the 31 days for April and May.
I am used to Java for loops and I am not familiar iterating over an nondeclared variable.
You need to reset the day back to one inside the outer loop otherwise day stays at 31 the second time through the loop. You can do this by moving the assignment inside the loop:
month = 3
for x in range(3):
day = 1
while day <= 31:
print(str(month)+"/"+str(day)+"/2019'")
day += 1
month += 1
Having said that, it's easier just to use for loops:
for month in range(3, 6):
for day in range(1, 32):
print(f"{month}/{day}/2019")
The only problem is that the variable day is not being reseted once a new month starts. You need to move the declaration day=1 inside the for-loop:
month = 3
for x in range(3):
day = 1
while day <= 31:
print(str(month)+"/"+str(day)+"/2019'")
day += 1
month += 1

I want to find the month name of 2018 where there are 5 Sundays or more

My problem is to find the month name of 2018 where there are 5 Sundays or more... I cannot do it. Does anyone has an idea how to solve this ?
You can just count it:
from collections import Counter
from datetime import date, timedelta
SUNDAY = 6
c = Counter()
for i in range(365):
day = date(2018, 1, 1) + timedelta(days=i)
if day.weekday() == SUNDAY:
c[day.month] += 1
# prints {4, 7, 9, 12}
print({month for month in c if c[month] >= 5})

Retrieve list of weekdays for any case

Hi everybody I have a small issue of coding:
I have a list of numbers from 0 to 6 that represent days of the week from Sunday to Saturday
So Sunday = 0 and Saturday = 6
So the list is [0,1,2,3,4,5,6]
There is no problem to retrieve the list between two days (or number) if the from < to.
example:
from Monday= 1 to Thursday= 4 there are these numbers included : [1,2,3,4]
Problems come when you have to retrieve the list of days when from > to:
example:
from Friday = 5 to Tuesday =2 we need to catch this list : [5, 6, 0, 1, 2]
Do you have idea how can I code an algorithm or a function that will give me a list of days (here numbers) to include if I give a number "from" and a number "to" whatever "from" is inferior or superior to the "to" value.
Thank you very much for your help.
I would do it this way:
def getweekdays(frm, to):
days = [0,1,2,3,4,5,6]
if frm <= to:
return days[frm:to+1]
else:
return days[frm:] + days[:to+1]
(I haven't checked the code, but you get the idea :) )
The easiest aproach for this would be:
day = first_day
while int day != last_day:
interval_days.add(day)
if day > 6:
day = 0
Initialize the day counter at the bottom limit of the day, then keep increasing the counter until the day matches the top limit, if it goes over the biggest day (6) you set it back into the first day of the week(0).
You can use list slicing:
s = [0,1,2,3,4,5,6]
days_of_week = dict(zip(['sun', 'mon', 'tue', 'wed', 'th', 'fri', 'sat'], s))
def get_days(day_range):
return range(days_of_week[day_range[0]], days_of_week[day_range[-1]]+1) if days_of_week[day_range[0]] <= days_of_week[day_range[-1]] else s[days_of_week[day_range[0]]:]+s[:days_of_week[day_range[-1]]+1]
ranges = [['fri', 'tue'], ['th', 'sat'], ['mon', 'th']]
print(list(map(get_days, ranges))))
Output:
[[5, 6, 0, 1, 2], [4, 5, 6], [1, 2, 3, 4]]
days_of_week = [0,1,2,3,4,5,6]
day_1 = 5
day_2 = 2
def days_needed(days_of_week, day_1, day_2, rollover=True):
if rollover:
day_list = days_of_week[day_1:day_2 - 1:-1]
else:
day_list = days_of_week[day_1:day_2 + 1]
return day_list
day_list = days_needed(days_of_week,day_1,day_2,rollover=True)
print(day_list)
This should do it. Let me know if you need any tweaking.

Find a day of week for given first day in month

How could be calculated a day of the week if we know the day number of the first day in month?
Lets say we have 1..7 days in a week
I want to get number of the 4th day in the month if the 1st = 5 (Friday) then result should be 1 (Monday).
1st - 5 Friday
2nd - 6 Saturday
3rd - 7 Sunday
4th - 1 Monday
(a=4, b=5) = 1
I tried to calculate the common formula:
result = (a + b - 1) % 7
So it works for all cases except the case when a = 3, 10, 17, 24, 31, because result = 0, but should be 7.
How can it be fixed to get this formula work for all days?
You need to avoid the result zero. Here is one way:
result = (a + b - 2) % 7 + 1
You subtract one more from your sum, to allow zero and work on the previous day, then you take the remainder modulo 7 to get the day which can include zero, then add one to get to the day wanted and avoid zero. Note that the order of operations will do the modulus before adding one. If you want to make that more explicit, you could use
result = ((a + b - 2) % 7) + 1

How do I perform timedelta and date comparison in Ruby?

In Python, if I want to check for a specific date + 24 hours has passed, I will write:
from datetime import datetime, timedelta
some_date = datetime(2013, 1, 10, 11, 0)
day = timedelta(1)
# Checks if some_date + 1 day is before today's date
print some_date + day < datetime.now()
How can I construct a time difference of 1 day and checks if a specific date + 1 day is before today's date in Ruby?
require 'time'
xmas = DateTime.new(2013, 12, 25)
puts x = xmas + 1 # 2013-12-26T00:00:00+00:00
d = DateTime.now
puts x > d # true
puts x - d # 30167183979194791/86400000000000 (a Rational)
puts d >> 12 # 2014-01-10T21:15:20+01:00

Categories

Resources