Python Date and time

 

Python Date and time

Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. Python enables us to schedule our Python script to run at a particular timing.

In Python, the date is not a data type, but we can work with the date objects by importing the module named with datetime, time, and calendar.

The datetime classes are classified in the six main classes.

  • date - It is a naive ideal date. It consists of the year, month, and day as attributes.
  • time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour, minute, second, microsecond, and tzinfo as attributes.
  • datetime - It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
  • timedelta - It represents the difference between two dates, time or datetime instances to microsecond resolution.
  • tzinfo - It provides time zone information objects.
  • timezone - It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.

Tick

In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time.

Time tuple

The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.

Index

Attribute

Values

0

Year

4 digit (for example 2018)

1

Month

1 to 12

2

Day

1 to 31

3

Hour

0 to 23

4

Minute

0 to 59

5

Second

0 to 60

6

Day of weak

0 to 6

7

Day of year

1 to 366

8

Daylight savings

-1, 0, 1 , or -1

 

Python sleep time

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 the number of seconds provided as the float.

The datetime Module

The datetime module enables us to create the custom date objects, perform various operations on dates like the comparison, etc.

To work with dates as date objects, we have to import the datetime module into the python source code.

Creating date objects

We can create the date objects bypassing the desired date in the datetime constructor for which the date objects are to be created.

Comparison of two dates

We can compare two dates by using the comparison operators like >, >=, <, and <=.

The calendar module

Python provides a calendar object that contains various methods to work with the calendars.

Consider the following example to print the calendar for the last month of 2018.

Printing the calendar of whole year

The prcal() method of calendar module is used to print the calendar of the entire year. The year of which the calendar is to be printed must be passed into this method.


0 Comments