0% found this document useful (0 votes)
6 views

Module 13

The document provides an overview of handling date and time in Python using the time and calendar modules. It explains various functions for getting current time, formatting time, and working with calendars, including examples of how to use these functions. Key methods such as time.time(), time.localtime(), and calendar.month() are highlighted for practical applications.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module 13

The document provides an overview of handling date and time in Python using the time and calendar modules. It explains various functions for getting current time, formatting time, and working with calendars, including examples of how to use these functions. Key methods such as time.time(), time.localtime(), and calendar.month() are highlighted for practical applications.

Uploaded by

ahad siddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Date and Time

Copyright © Nex-G | Skills , NESPL


1
1
Date & Time

• A Python program can handle date and time in several ways. Converting between date formats is
a
common chore for computers. Python's time and calendar modules help track dates and times.

Tick : Time intervals are floating-point numbers in units of seconds. Particular instants in time are
expressed in seconds since 12:00am, January 1, 1970(epoch).

There is a popular time module available in Python which provides functions for working with
times, and for converting between representations. The function time.time() returns the current
system time in ticks since 12:00am, January 1, 1970(epoch).

Example

import time # This is required to include time module.

ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)

This would produce a result something as follows −


Number of ticks since 12:00am, January 1, 1970: 1636882115.402384

Copyright © Nex-G | Skills , NESPL 2


TimeTuple: Many of Python's time functions handle time as a tuple of 9 numbers, as shown below −

Index Field Values

0 4-digit year 2008

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are


leap-seconds)
6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means


library determines
DST

Copyright © Nex-G | Skills , NESPL 3


Tuple is equivalent to struct_time structure. This structure has following attributes −

Index Attributes Values

0 tm_year 2008

1 tm_mon 1 to 12

2 tm_mday 1 to 31

3 tm_hour 0 to 23

4 tm_min 0 to 59

5 tm_sec 0 to 61 (60 or 61 are leap-seconds)

6 tm_wday 0 to 6 (0 is Monday)

7 tm_yday 1 to 366 (Julian day)

8 tm_isdst -1, 0, 1, -1 means library determines DST

Copyright © Nex-G | Skills , NESPL 4


Getting current time: To translate a time instant from a seconds since the epoch floating-point value into
a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all
nine items valid.

import time

localtime = time.localtime(time.time())
print("Local current time :", localtime)

This would produce the following result, which could be formatted in any other presentable form −

Local current time : time.struct_time(tm_year=2021, tm_mon=11, tm_mday=14, tm_hour=15, tm_min=5,


tm_sec=4, tm_wday=6, tm_yday=318, tm_isdst=0)

Copyright © Nex-G | Skills , NESPL 5


Getting formatted time: You can format any time as per your requirement, but simple method to get
time in readable format is asctime() −

import time

localtime = time.asctime( time.localtime(time.time()) )


print("Local current time :", localtime)

This would produce the following result −

Local current time : Sun Nov 14 15:06:39 2021

OR I would recommend you just use the ctime() function

import time

localtime = time.ctime()
print("Local current time :", localtime)

And this would output the exact same thing.

Copyright © Nex-G | Skills , NESPL 6


Getting calendar for a month:

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here,
we print a calendar for a given month ( Jan 2008 ) −

import calendar

cal = calendar.month(2021, 11)


print("Here is the calendar:")
print(cal)

This would produce the following result −

Here is the calendar:


November 2021
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

Copyright © Nex-G | Skills , NESPL 7


The time Module: There is a popular time module available in Python which provides functions for
working with times and for converting between representations. Here is the list of all available
methods.

1) time altzone() : The method altzone() is the attribute of the time module. This returns the offset of
the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST
timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.

Example

The following example shows the usage of altzone() method.

import time

print("time.altzone:", time.altzone)

When we run above program, it produces following result:

time.altzone: -23400

Copyright © Nex-G | Skills , NESPL 8


2) time asctime(): The method asctime() converts a tuple or struct_time representing a time as returned
by gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'.

Example:-
The following example shows the usage of asctime() method.

import time

t = time.localtime()
print("time.asctime(t):", time.asctime(t))
When we run above program, it produces following result:

time.asctime(t): Sun Nov 14 15:16:04 2021

Copyright © Nex-G | Skills , NESPL 9


3) time clock() :
THE METHOD time.clock() HAS BEEN REMOVED IN PYTHON 3.8.
Use the following code to check time of execution of your code.
Example
import time

def procedure():
time.sleep(2.5)

# measure wall time


t0 = time.time()
procedure()
print(time.time() - t0, "seconds wall time")

When we run above program, it produces following result:


2.5151777267456055 seconds wall time

Copyright © Nex-G | Skills , NESPL 10


4) time ctime() : The method ctime() converts a time expressed in seconds since the epoch to a string
representing local time. If secs is not provided or None, the current time as returned by time() is used.
This function is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

Example

The following example shows the usage of ctime() method.

import time

print("time.ctime() :", time.ctime())

When we run above program, it produces following result:

time.ctime() : Sun Nov 14 15:22:58 2021

Copyright © Nex-G | Skills , NESPL 11


5) time gmtime(): The method gmtime() converts a time expressed in seconds since the epoch to a
struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time
as returned by time() is used.

Example

The following example shows the usage of gmtime() method.

import time

print("time.gmtime():" , time.gmtime())

When we run above program, it produces following result:

time.gmtime(): time.struct_time(tm_year=2021, tm_mon=11, tm_mday=14, tm_hour=9, tm_min=54,


tm_sec=11, tm_wday=6, tm_yday=318, tm_isdst=0)

But making one small change (add the asterisks in front of time.gmtime()):
print("time.gmtime():" , *time.gmtime())
Produces:
time.gmtime(): 2021 11 14 9 54 27 6 318 0

Copyright © Nex-G | Skills , NESPL 12


6) time localtime(): The method localtime() is similar to gmtime() but it converts number of seconds to
local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag
is set to 1 when DST applies to the given time.

Example

The following example shows the usage of localtime() method.

import time

print("time.localtime():", *time.localtime())

When we run above program, it produces following result:

time.localtime(): 2021 11 14 15 27 43 6 318 0

Copyright © Nex-G | Skills , NESPL 13


7) time mktime(): The method mktime() is the inverse function of localtime(). Its argument is the
struct_time or full 9-tuple and it returns a floating point number, for compatibility with time().

If the input value cannot be represented as a valid time, either OverflowError or ValueError will be
raised.

Example
The following example shows the usage of mktime() method.

import time

t = (2021, 11, 14, 15, 27, 43, 6, 318, 0)


secs = time.mktime( t )
print("time.mktime(t):", secs)
print ("asctime(localtime(secs)):", time.asctime(time.localtime(secs)))

When we run above program, it produces following result:

time.mktime(t): 1636883863.0
asctime(localtime(secs)): Sun Nov 14 15:27:43 2021

Copyright © Nex-G | Skills , NESPL 14


8) time sleep(): The method sleep() suspends execution for the given number of seconds. The
argument may be a floating point number to indicate a more precise sleep time.

The actual suspension time may be less than that requested because any caught signal will terminate
the sleep() following execution of that signal's catching routine.

Example
The following example shows the usage of sleep() method.

import time

print("Start :" , time.ctime())


time.sleep( 5 )
print("End :", time.ctime())

When we run above program, it produces following result:

Start : Sun Nov 14 15:44:45 2021


End : Sun Nov 14 15:44:50 2021

Copyright © Nex-G | Skills , NESPL 15


9) time strftime(): The method strftime() converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a string as specified by the format argument.

If t is not provided, the current time as returned by localtime() is used. format must be a string. An
exception ValueError is raised if any field in t is outside of the allowed range.

Example

The following example shows the usage of strftime() method.

import time

t = (2021, 11, 14, 15, 27, 43, 6, 318, 0)


t = time.mktime(t)
print(time.strftime("%b %d %Y %H:%M:%S", time.gmtime(t)))

When we run above program, it produces following result:

Nov 14 2021 09:57:43

Copyright © Nex-G | Skills , NESPL 16


10) time strptime(): The method strptime() parses a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d
%H:%M:%S %Y" which matches the formatting returned by ctime().

If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is
raised.

Example

The following example shows the usage of strptime() method.

import time

struct_time = time.strptime("30 Nov 00", "%d %b %y")


print("returned tuple: ", struct_time)

When we run above program, it produces following result:

returned tuple: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,


tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

Copyright © Nex-G | Skills , NESPL 17


11) time time() : The method time() returns the time as a floating point number expressed in seconds
since the epoch, in UTC.
Note: Even though the time is always returned as a floating point number, not all systems provide time
with a better precision than 1 second. While this function normally returns non-decreasing values, it
can return a lower value than a previous call if the system clock has been set back between the two
calls.

Example

The following example shows the usage of time() method.

import time

print("time.time():", time.time())
print(time.localtime(time.time()))
print(time.asctime(time.localtime(time.time())))

When we run above program, it produces following result:

time.time(): 1636885442.4242332
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=14, tm_hour=15, tm_min=54, tm_sec=2,
tm_wday=6, tm_yday=318, tm_isdst=0)
Sun Nov 14 15:54:02 2021

Copyright © Nex-G | Skills , NESPL 18


The calendar Module

The calendar module supplies calendar-related functions, including functions to print a


text calendar for a given month or year.
By default, calendar takes Monday as the first day of the week and Sunday as the last
one. To change this, call calendar.setfirstweekday() function.
Here is a list of functions available with the calendar module:

Copyright © Nex-G | Skills , NESPL 19


SN Function with Description
Returns a multiline string with a calendar for
year year formatted into three columns
1 > calendar.calendar(year,w=2,l=1,c=6) separated by c spaces. w is the width in
characters of each date; each line has length
21*w+18+2*c. l is the number of lines for
each week.
Returns the current setting for the weekday
2 >calendar.firstweekday( ) that starts each week. By default, when
calendar is first imported, this is 0, meaning
Monday.
3 > calendar.isleap(year) Returns True if year is a leap year; otherwise,
False.
4> calendar.leapdays(y1,y2) Returns the total number of leap days in the
years within range(y1,y2).
Returns a multiline string with a calendar for
month month of year year, one line per week
5> calendar.month(year,month,w=2,l=1) plus two header lines. w is the width in
characters of each date; each line has length
7*w+6. l is the number of lines for each week.

Copyright © Nex-G | Skills , NESPL 20


SN Function with Description
Returns a list of lists of ints. Each sublist
6> calendar.monthcalendar(year,month) denotes a week. Days outside month month of
year year are set to 0; days within the month
are set to their day-of-month, 1 and up.
Returns two integers. The first one is the code
of the weekday for the first day of the month
7>calendar.monthrange(year,month) month in year year; the second one is the
number of days in the month. Weekday codes
are 0 (Monday) to 6 (Sunday); month numbers
are 1 to 12.
8 > calendar.prcal(year,w=2,l=1,c=6) Like print calendar.calendar(year,w,l,c).
9> calendar.prmonth(year,month,w=2,l=1) Like print calendar.month(year,month,w,l).
Sets the first day of each week to weekday
10> calendar.setfirstweekday(weekday) code weekday. Weekday codes are 0 (Monday)
to 6 (Sunday).

Copyright © Nex-G | Skills , NESPL 21


SN Function with Description

The inverse of time.gmtime: accepts a time


11> calendar.timegm(tupletime) instant in time-tuple form and returns the same
instant as a floating-point number of seconds
since the epoch.

Returns the weekday code for the given date.


12>calendar.weekday(year,month,day) Weekday codes are 0 (Monday) to 6 (Sunday);
month numbers are 1 (January) to 12
(December).

Copyright © Nex-G | Skills , NESPL 22

You might also like