Pyth Unit IV
Pyth Unit IV
In Python, date and time are not a data type of their own, but a module named datetime can be
imported to work with the date as well as time. Python Datetime module comes built into
Python, so there is no need to install it externally.
Python Datetime module supplies classes to work with date and time. These 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
string or timestamps.
date – An idealized naive date, assuming the current Gregorian calendar always was,
and always will be, in effect. Its attributes are year, month and day.
time – An idealized time, independent of any particular day, assuming that every day
has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond,
and tzinfo.
datetime – Its a combination of date and time along with the attributes year, month,
day, hour, minute, second, microsecond, and tzinfo.
timedelta – A duration expressing the difference between two date, time, or datetime
instances to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – A class that implements the tzinfo abstract base class as a fixed offset from
the UTC (New in version 3.2).
Date class
The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs
three mandatory arguments year, month and date.
# Python program to
# demonstrate date class
# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)
To return the current local date today () function of date class is used. today () function comes
with several attributes (year, month and day). These can be printed individually.
# Python program to
# print current date
Output
Today's date is 2021-08-19
We can get the year, month, and date attributes from the date object using the year, month
and date attribute of the date class.
Output
Current year: 2021
Current month: 8
Current day: 19
We can create date objects from timestamps y=using the fromtimestamp () method. The
timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.
fromisoformat() Returns a date object from the string representation of the date
Returns a date object from the proleptic Gregorian ordinal, where January
fromordinal()
1 of year 1 has ordinal 1
Returns the day of the week as integer where Monday is 1 and Sunday is
isoweekday()
7
replace() Changes the value of the date object with the given parameter
strftime() Returns a string representation of the date with the given format
Returns the day of the week as integer where Monday is 0 and Sunday is
weekday()
6
List of Time class Methods
Function Name Description
fromisoformat() Returns a time object from the string representation of the time
isoformat() Returns the string representation of time from the time object
replace() Changes the value of the time object with the given parameter
strftime() Returns a string representation of the time with the given format
combine() Combines the date and time objects and return a DateTime object
Returns a datetime object from the string representation of the date and
fromisoformat()
time
Returns the day of the week as integer where Monday is 1 and Sunday
isoweekday()
is 7
Returns the day of the week as integer where Monday is 0 and Sunday
weekday()
is 6
Calendar Module
Python defines an inbuilt module calendar that handles operations related to the calendar.
The calendar module allows output calendars like the program and provides additional useful
functions related to the calendar. Functions and classes defined in the Calendar module use an
idealized calendar, the current Gregorian calendar extended indefinitely in both directions. By
default, these calendars have Monday as the first day of the week, and Sunday as the last (the
European convention).
Example #1: Display the Calendar of a given month.
# Python program to display calendar of
# given month of the year
# import module
import calendar
yy = 2017
mm = 11
The calendar class creates a Calendar object. A Calendar object provides several methods that
can be used for preparing the calendar data for formatting. This class doesn’t do any formatting
itself. This is the job of subclasses. Calendar class allows the calculations for various tasks
based on date, month, and year. Calendar class provides the following methods:
Function Description
Returns an iterator for the week day numbers that will be used for
iterweekdays()
one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
Method is used to get an iterator for the month in the year similar to
itermonthdays2() itermonthdates(). Days returned will be tuples consisting of a day of
the month number and a week day number.
Returns an iterator for the month in the year similar to
itermonthdates(), but not restricted by the datetime.date range. Days
itermonthdays3()
returned will be tuples consisting of a year, a month and a day of the
month numbers.
Returns an iterator for the month in the year similar to
itermonthdays4()
itermonthdates(), but not restricted by the datetime.date range. Days
returned will be tuples consisting of a year, a month, a day of the
month, and a day of the week numbers.
monthdatescalendar() Used to get a list of the weeks in the month of the year as full weeks
monthdays2calendar() Used to get a list of the weeks in the month of the year as full weeks
monthdayscalendar Used to get a list of the weeks in the month of the year as full weeks
yeardatescalendar() Used to get a list of the weeks in the month of the year as full weeks
Used to get the data for specified year. Entries in the week lists are
yeardays2calendar()
tuples of day numbers and weekday numbers
Used to get the data for specified year. Entries in the week lists are
yeardayscalendar()
day numbers
Math Module
Sometimes when working with some kind of financial or scientific projects it becomes
necessary to implement mathematical calculations in the project. Python provides the math
module to deal with such calculations. Math module provides functions to deal with both basic
operations such as addition (+), subtraction (-), multiplication (*), division (/) and advance
operations like trigonometric, logarithmic, exponential functions.
Math module provides various the value of various constants like pi, tau. Having such constants
saves the time of writing the value of each constant every time we want to use it and that too
with great precision. Constants provided by the math module are –
Euler’s Number
Pi
Tau
Infinity
Not a Number (NaN)
Euler’s Number
Syntax:
math.e
# Import math Library
import math
print (math.e)
Pi
You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. math.pi provides a
more precise value for the pi.
Syntax:
math.pi
import math
print (math.pi)
Tau
Tau is defined as the ratio of the circumference to the radius of a circle. The math.tau
constant returns the value tau: 6.283185307179586.
Syntax:
math.tau
import math
print (math.tau)
Infinity
Infinity basically means something which is never-ending or boundless from both directions
i.e. negative and positive. It cannot be depicted by a number. The math.inf constant returns
of positive infinity. For negative infinity, use -math.inf.
Syntax:
math.inf
import math
print (math.inf)
print (-math.inf)
NaN
The math.nan constant returns a floating-point nan (Not a Number) value. This value is not a
legal number. The nan constant is equivalent to float(“nan”).
import math
print (math.nan)
List of Mathematical function in Python
Python File
Files are identified locations on the disc where associated data is stored. They are used to retain
data in non-volatile memory indefinitely (e.g. hard disk). Because Random Access Memory
(RAM) is volatile (it loses data when the computer is shut off), we employ files to store data
for future use by permanently storing it.
When we wish to read or write to a file, we must first open it. When we’re finished, it needs to
be closed so that the resources associated with the file may be released. As a result, Python file
operations occur in the following order:
Opening a file
Reading or writing a file (perform operation)
Closing the file
In Python, there are two sorts of files that can be handled: text files and binary files (written in
binary language- 0s and 1s)
Binary files – The majority of files you use on a regular basis on your computer are
binary files, not text ones. That’s right, even though it only contains text, the Microsoft
Word.doc file is a binary file. There is no line terminator in this form of a file, and the
data is kept after it has been converted into machine-readable binary language.
Text files – A text file, on the other hand, does not require any special encoding and
may be opened with any ordinary text editor. Each line of text in this sort of file is
terminated with a special character known as EOL (End of Line), which is the new line
character (‘\n’) in Python by default.
To open a file, Python includes the open () function. This function returns a file object, often
known as a handle, which is used to read or change the file. This function does not require the
import of any modules.
where,
filename – name of the file that the file object has to open
access_mode – attribute of the file that tells which mode a file was opened in. Default
is reading in text mode
Mode Description
r Allows you to open a file for reading. (default)
This command opens a file for writing. If the file does not exist, it is
w
created; otherwise, it is truncated.
Opens a file for adding at the end without truncating it. If the file
a
does not exist, it is created.
Files are useless if you can’t write data to them. To accomplish this, we can employ the Python
write () function. This adds the characters you specify to the end of a file. Keep in mind that
when you create a new file object, Python will create the file if it does not already exist. When
making your first file, you should utilize either the a+ or w+ modes. We must exercise caution
when using the w mode, as it will overwrite the file if it already exists. As a result, all previous
data is deleted.
1. Python write() –
Inserts the string str1 into the text file on a single line.
File_object.write(str1)
2. Python writelines() –
Each string is inserted into the text file for a list of string elements. Used to insert many
strings at once.
Example
Output
5 eggs
2 tsp baking powder
60g butter
2 cup sugar
To begin reading a file in Python, open the file you wish to read. Python requires you to specify
the name and location of the file you want to open. To read a file in Python, we must first open
it in reading r mode. To read data from a file, we can use one of three functions, which are as
follows:
1. Python read() –
The fileobject.read(size) method is used to read the contents of a file. If no size option
is specified, this method will read the full file and send it to the console as a string (in
text mode) or as byte objects (in binary mode). The size parameter instructs the read
method how many bytes to return to the display from the file.
File_object.read([n])
>>> f.read() # reads the rest of the data till the end of file
' butter\n2 cup sugar\n2 cup water\n250ml skimmed milk\n'
2. Python readline() –
Data in a file can also be parsed by reading it line by line. This allows you to scan an
entire file line by line, progressing only when necessary. Reads a line from a file and
returns it as a string. Reads at most n bytes for the provided n. However, even if n is
greater than the length of the line, does not read more than one line.
File_object.readline([n])
>>> f.readline()
'2 tsp baking powder\n'
>>> f.readline()
'60g butter\n'
>>> f.readline()
'2 cup sugar\n'
3. Python readlines() –
The fileobject.readlines() method (note the plural), which produces a list of all the lines
in the file. This method reads all the lines and returns them as string elements in a list,
one for each line.
File_object.readlines()
To conduct various Python file operations with the help of file objects, you may use a variety
of methods. Some of them were utilized in the above examples. Let us look at some more
Python file operation methods below:
Method Description
This function closes an open file. If the file is already closed, it
close()
has no effect.
Returns the underlying binary buffer after separating it from the
detach()
TextIOBase.
fileno() The file’s integer number (file descriptor) is returned.
flush() Flushes the file stream’s write buffer.
isatty() If the file stream is interactive, this method returns True.
Reads a maximum of n characters from the file. If it is negative
read(n)
or None, it reads till the end of the file.
readable() If the file stream can be read from, this method returns True.
Reads one line from the file and returns it. If n is supplied, it
readline(n=-1)
reads in at most n bytes.
Reads the file and returns a list of lines. If n bytes/characters are
readlines(n=-1)
given, this function reads in at most n bytes/characters.
Changes the file position in reference to from to offset bytes
seek(offset,from=SEEK_SET)
(start, current, end).
If the file stream enables random access, this function returns
seekable()
True.
tell() The current file location is returned.
The file stream is resized to size bytes. If no size is supplied, it
truncate(size=None)
resizes to the current position.
writable() If the file stream can be written to, this method returns True.
Returns the number of characters written after writing the string
write(s)
s to the file.
writelines(lines) A list of lines is written to the file.