Showing posts with label Date. Show all posts
Showing posts with label Date. Show all posts

program to find number of days between two given dates

class Date:

def __init__(self, d, m, y):

self.d = d

self.m = m

self.y = y

monthDays = [31, 28, 31, 30, 31, 30,

31, 31, 30, 31, 30, 31]

def countLeapYears(d):

years = d.y

if (d.m <= 2):

years -= 1

return int(years / 4) - int(years / 100) + int(years / 400)

def getDifference(dt1, dt2):

n1 = dt1.y * 365 + dt1.d

for i in range(0, dt1.m - 1):

n1 += monthDays[i]

n1 += countLeapYears(dt1)

n2 = dt2.y * 365 + dt2.d

for i in range(0, dt2.m - 1):

n2 += monthDays[i]

n2 += countLeapYears(dt2)

return (n2 - n1)

dt1 = Date(13, 12, 2018)

dt2 = Date(25, 2, 2019)

print(getDifference(dt1, dt2), "days")


Program to convert DateTime to string

import time

def convert(datetime_str):

datetime_str = time.mktime(datetime_str)

format = "%b %d %Y %r" 

dateTime = time.strftime(format, time.gmtime(datetime_str))

return dateTime

date_time = (2018, 12, 4, 10, 7, 00, 1, 48, 0)

print(convert(date_time))


Find number of times every day occurs in a Year

import datetime

import calendar

def day_occur_time(year):

days = [ "Monday", "Tuesday", "Wednesday",

"Thursday", "Friday", "Saturday",

"Sunday" ]

L = [52 for i in range(7)]

pos = -1

day = datetime.datetime(year, month = 1, day = 1).strftime("%A")

for i in range(7):

if day == days[i]:

pos = i

if calendar.isleap(year):

L[pos] += 1

L[(pos+1)%7] += 1

else:

L[pos] += 1

for i in range(7):

print(days[i], L[i])

year = 2020

day_occur_time(year)


Program to Create a Lap Timer

import time

starttime=time.time()

lasttime=starttime

lapnum=1

print("Press ENTER to count laps.\nPress CTRL+C to stop")

try:

while True:

input()

laptime=round((time.time() - lasttime), 2)

totaltime=round((time.time() - starttime), 2)

print("Lap No. "+str(lapnum))

print("Total Time: "+str(totaltime))

print("Lap Time: "+str(laptime))

print("*"*10)

lasttime=time.time()

lapnum+=1

except KeyboardInterrupt:

print("Done")


Program to find yesterday’s, today’s and tomorrow’s date

from datetime import datetime, timedelta

currentday = datetime.now()

yesterday = currentday - timedelta(1)

tomorrow = currentday + timedelta(1)

print("Yesterday = ", yesterday.strftime('%d-%m-%Y'))

print("Today = ", currentday.strftime('%d-%m-%Y'))

print("Tomorrow = ", tomorrow.strftime('%d-%m-%Y'))


Python program to find day of birth

import datetime
y = input("Enter year of Birth: ");
m = input("Enter month of Birth: ");
d = input("Enter date of Birth: ");
mydate = datetime.date(int(y),int(m),int(d))
print(mydate.strftime("%A"))

Python program to print date and time

import datetime;
print("Today Date & Time:\n");
print(datetime.datetime.today());