Python Programming - Date and Time Functions

You can learn about Functions in Python Programs with Outputs helped you to understand the language better.

Python Programming – Date and Time Functions

Classes provide a number of functions to deal with dates, times, and time intervals. Date and DateTime are an object in Python, so when you manipulate them, you are actually manipulating objects and not strings or timestamps. Whenever you manipulate dates or times, you need to import the DateTime function. The DateTime module enables you to create the cus¬tom date objects, and perform various operations on dates like the comparison, etc. To work with dates as date objects, you have to import the DateTime module into the Python source code.

The concept of Ticks

In Python, the time instants are counted since 12:00 am, January 1, 1970. It is the beginning of an era. and is used to start counting time. This special moment is called an epoch. In Python, the time between the present moment and the special time above is expressed in seconds. That time period is called Ticks. A tick can be seen as the smallest unit to measure the time. The time ( ) function in the time module returns the number of seconds from 12 am on January 1, 1970, to the present.

Example
Demo to calculate the number of ticks using the time ( ) function

# Import time module
import time# prints the number of ticks spent since 12 AM, 1st January 1970
ticks = time.time ( )
print (“Number of ticks since 12:00am, January 1, 1970: “, ticks)RUN
>>>
1560653863.8000364
>>>

time ( )

To get how many ticks have passed since the epoch, you call the Python time ( ) method.
>>> import time
>>> time. time ( )
1514472378. 761928
A time object instantiated from the time class represents the local time.

Example
Demo of time ( ) function.

from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time ( )
print(“a =”, a)
# time(hour, minute and second)
b = time(9, 32, 52)
print(“b =”, b)
# time(hour, minute and second)
c = time(hour = 9, minute = 32, second = 52)
print(“c =”, c)
# time(hour, minute, second, microsecond)
d = time(9, 32, 52, 224565)
print(nd =”, d)RUN
>>>
a = 00:00:00
b = 09:32:52
c = 09:32:52
d = 09:32:52.224565
>>>

Example
Program to print hour, minute, second and microsecond.

# Print hour, minute, second and microsecond
from datetime import time
a = time(9, 32, 52)print(“hour =”, a.hour)
print(“minute =”, a.minute)
print(“second =”, a.second)
print(“microsecond =”, a.microsecond)RUN
>>>
hour = 9
minute = 32
second = 52
microsecond = 0
>>>

Once you create a time object, you can easily print its attributes such as hour, minute, etc. Note that you have not passed the microsecond argument, so, its default value 0 is printed.

local time ( )

local time ( ) returns the current time according to your geographical location, in a more readable format. Consider the following example.

Example
Demo of localtime ( ) function.

import time

#returns a time tuple

print(time.localtime(time.time( )))

RUN
>>>
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=16, tm_hour=8, tm_min=28, tm_sec=59, tm_wday=6, tm_yday=167, tm_isdst=0)
>>>

asctime ( )

The time can be formatted by using the asctime ( ) function of the time module. It returns the formatted time for the time tuple being passed.
>>> import time
>>> time.asctime ( )
‘Sun Jun 16 11:18:09 2019’

clock ( )

It returns the number of seconds elapsed since the first call made to it. It returns the value as a floating number.
>>> time.clock ( )
1392.736455535
>>> time.clock ( )
1409.408693707

sleep ( )

The sleep ( ) method of time module is used to stop the execution of the script for a given amount of time. The output will be delayed for a number of seconds. Consider the following example.

Example
Demo of sleep ( ) function.

import time
for i in range(0,5):
print(i)
#Each element will be printed after 2 second
time.sleep(2)RUN
>>>
0
1
2
3
4
>>>

now ( )

The now ( ) method to create a DateTime object containing the current local date and time. The date contains the year, month, day, hour, minute, second, and microsecond.

Example
Demo of now ( ) function.

# Get Current Date and Time
import datetime;#returns the current datetime objectprint(datetime.datetime.now())RUN
>>>
2019-06-16 08:36:33.975566
>>>

today ( )

today ( ) method defined in the date class to get a date object containing the current local date.

Example
Demo of today ( ) function.

# Get Current Date

import datetime;
date_object = datetime.date.today ( )
print(date_object)
RUN
>>>
2019-06-16
>>>

Example
Demo of today ( ) function.

# Print today’s year, month and day
from datetime import date
today = date.today ( )
print(“Current year:”, today.year)
print(“Current month:”, today.month)
print(“Current day:”, today.day)RUN
>>>
Current year: 2019
Current month: 6
Current day: 16
>>>

date ( )

The date() is a constructor of the date class. It takes three arguments: year, month, and day.

Example
Demo of date ( ) function.

# Date object to represent a date
import datetime
d = datetime.date(2019, 7, 12)
print(d)RUN
>>>
2019-07-12
>>>

dir ( )

The dir ( ) function to get a list containing all attributes of a module.

Example
Demo of dir ( ) function.

import datetime
print(dir(datetime))RUN
>>>
[‘MAXYEAR’, ‘ M INYEAR’ , ‘ built ins ‘ , ‘ cached ‘ loader me_CAPI’, ‘ ‘, ‘ name ‘, ‘ package ‘, time’, ‘timedelta’, ‘timezone’ ‘ spec ‘, ‘ ‘tzinfo’]
>>>

timestamp ( )

You can also create date objects from a timestamp. You can convert a timestamp to date using from timestamp ( ) function.

Example
Demo of timestamp ( ) function.

from datetime import date
print(“Date timestamp)RUN
>>>
Date : 2021-07-14
>>>

strftime ( )

The strftime ( ) method takes one or more format codes and returns a formatted string based on it. A reference of some format codes are used in following example:

Example
Demo of strftime ( ) function.

import datetime
x = datetime.datetime . now ( )
print(x.year)
print(x.strftime(“%a”) )             #Weekday, short version i.e. Sun
print(x.strftime(“%A”) )            #Weekday, full version i.e. Sunday
print(x.strftime(“%w”) )            #Weekday as a number 0-6 i.e. 0
print(x.strftime(“%d”) )            #Day of month 01-31 i.e. 16
print(x.strftime(“%b”) )            #Month name, short version i.e. Jun
print(x.strftime(“%B”) )            #Month name, full version i.e. June
print(x.strftime(“%m”) )          #Month as a number 01-12 i.e. 06
print(x.strftime(“%y”) )           #Year, short version, without century i.e. 19
print(x.strftime(“%Y”) )           #Year, full version i.e., 2019
print(x.strftime(“%H”) )          #Hour 00-23 i.e. 11
print(x.strftime(“%I”) )           #Hour 00-12 i.e. 11
print(x.strftime(“%p”) )          #AM/PM i.e. AM
print(x.strftime(“%M”) )        #minute 00-59 i.e. 02
print(x.strftime(“%S”) )         #second 00-59 i.e. 59
print(x.strftime(‘%c”) )          #Local version of date and time i.e. sun Jun 16 11 : 02 : 59 2019
print(x.strftime(‘”%x”))        #Local version of date i.e. 06/16/19
print(x.strftime(“%X”))        #Local version of time i.e. 11:02:59RUN
>>>
2019
Sun
Sunday
0
16
Jun
June
06
19
2019
11
11
AM
02
59
Sun Jun 16 11:02:59 2019
06/16/19
11:02:59
>>>

Date Arithmetic

Example
Demo of Date Arithmetic.

import datetime
today = datetime.date.today ( )
print(‘Today :’, today)
oneday = datetime.timedelta(days=1)
print(‘One day :’, one_day)
yesterday = today – one_day
print (‘Yesterday:’, yesterday)
tomorrow = today + one_day
print (‘Tomorrow :’, tomorrow)RUN
>>>
Today : 2019-06-16
One day : 1 day, 0:00:00
Yesterday: 2019-06-15
Tomorrow : 2019-06-17
>>>

The calendar module

Python provides a calendar object that contains month ( ) function.

#Program to print the calendar of July 2019
print(calendar.month(2019,7))RUN
>>>
July 2019
Mo  Tu  We  Th  Fr  Sa  Su
1      2     3     4
5     6      7      8      9     10
11  12    13    14     15    16
17  18    19    20     21    22
23   24   25   26     27     28
29   30   31
>>>
>> print(calendar.month(2020,1))

January 2020
Mo  Tu  We  Th  Fr  Sa  Su
1      2    3     4    5   6     7
8      9   10  11   12  13  14
15   16  17   18   19  20  21
22   23  24   25   26  27  28
29   30 31

You can also print the calendar for the whole year. The partial ( ) method of the calendar module is used to print the calendar of the whole year. (See Figure 10.58).

# Printing the calendar of whole year
import calendar

#printing the calendar of the year 2019
calendar.parcel(2019)

isleap ( )

The isleap ( ) takes a 4-digit year as an argument, and returns True if it is a leap year. Otherwise, False.
>>> calendar.isleap(2019)
False
>>> calendar.isleap(2020)
True

Leapdays(y1 ,y2)
The leapdays ( ) returns the total number of leap days from year yl to year y2.
>>> calendar.leapdays(1990,2020)
7

firstweekday ( )

The firstweekday ( ) returns which day is currently set as the first day of the week.
>>> calendar.setfirstweekday(O)
>>> calendar.firstweekday ( )
0

Python Programming - Date and Time Functions chapter 10 img 1

Recursion

Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. You know that in Python, a function can call other functions. It is even possible for the function to call itself. These types of the construct are termed recursive functions.

For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120 is a recursive function to find the factorial of an integer. The factorial function is widely used in the combinatorial analysis (counting theory in mathematics), probability theory, and statistics. The factorial of n usually is expressed as n!. Factorial is defined as non-negative integers.

Example
Program to find factorial using recursion

def calc_fact(x):
if x == 1:
return 1
else:
return (x * calc_fact(x-1))num = 5
print(“The factorial of”, num, “is”, calcfact(num))RUN
>>>
The factorial of 5 is 120
>>>

In the above example, calc_fact ( ) is a recursive function as it calls itself. When you call this function with a positive integer, it will recursively call itself by decreasing the number. Each function calls multiples the number with the factorial of number 1 until the number is equal to one. The recursion ends when the number reduces to 1, which is called the base condition. Every recursive function must have a base condition that stops or terminates the recursion or else the function calls itself infinitely.

Example
Program to find the power of a number using recursion.

# To find the power of a number using recursion
def power(base,exp):
if (exp==1):
return base
if (exp!=1):
return (base*power(base,exp-1))
base = int(input(“Enter base: “))
exp = int(input(“Enter exponential value: “))
print (“Result:”,power(base,exp))RUN
>>>
Enter base: 4
Enter exponential value: 3
Result: 64
>>>

In the above example, power ( ) is a recursive function as it calls itself. When a user enters the base and exponential value, the numbers are passed as arguments to a recursive function to find the power of the number. The base condition is given that if the exponential power is equal to 1, the base number is returned. If the exponential power is not equal to 1, the base number multiplied with the power function is called recursively with the arguments as the base and power minus 1 and the final result is printed.

Advantages of Recursion

  1. Recursive functions make the code look clean and refined.
  2. A complex task can be broken down into simpler sub-problems using recursion.
  3. Sequence generation is easier with recursion than using some nested iteration

Disadvantages of Recursion

  1. Sometimes the logic behind recursion is difficult to follow through.
  2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
  3. Recursive functions are hard to debug.

Recommended Reading On PTSP Notes

Must Read:

FEDERALBNK Pivot Point Calculator

Leave a Reply

Your email address will not be published. Required fields are marked *