Python – Date and Time

Date and Time in Python

We would cover date and time data type in Python. Then we learn how to convert date and time data.

 

We would cover the following

  1. What is a Tick?
  2. Basics of Time Tuple
  3. Formatting Time Data
  4. Creating a Calendar
  5. The time Module
  6. The calendar Module

 

 

Let’s start by explaining the concept of tick

1. What is a Tick?

A tick is an interval of time in Python given in seconds. This is number of seconds from 12:00 a.m, January 1 1970.

Python contains a module called time. This modules provides what you need to work with time in Python. To use it, you need to add import time statement.

So to get the current time, you use the function time.time(). Let’s see how it work.

 

import time

currentTime = time.time()
print(currentTime)

 

The above code would give the output of 1549478219.6221974. This is because it returns time in seconds.

 

2. Basics of Time Tuple

You remember a tuple is a collection of items. You can review tuples here. Now, in Python, time is represented as a tuple of 9 items. These 9 items are explained in the table below

Index Field Values
0 4-digit year 2019
1 Month number 1 to 12
2 Day of month 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 number 0 to 6 (0 is Monday, 1 is Tuesday, etc)
7 Day of year 1 to 366 (Julian day)
8 Daylight savings -1, 0, 1, -1 means library determines DST

 

3. Formatting Time Data

You can get formatted time by using the format by using the asctime() function. This would produce time in a friendly format.

For example

import time

currentTime = time.asctime()
print(currentTime)

If you run the code above, then you will have a formatted time as shown below:

Wed Feb  6 22:27:33 2019

 

 

4. Creating a Calendar

You can create and display a calendar in Python. You can do this using functions in the calendar module. Therefore, you need to import the calendar module.

For example, the code below would create a calendar.

import calendar

# Calender of February 2019
mycalendar = calendar.month(2019, 2)
print("Current Calendar")
print(mycalendar)

 

If your run the code below, a calendar would be formatted and displayed as shown in below.

Current Calendar
   February 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

 

 

5. The time Module

The time module in Python provides many methods you can use to manipulate time. Especially for converting times between different formats.

Table below provides a list of methods available in the time module.

SN Function and brief description
1 time.altzoneGives the offset of the local DST timezone, in seconds west of UTC, if defined. It would be negative if the local DST timezone is east of UTC.You need to use this only if daylight is nonzero.
2 time.asctime([tupletime])Returns a readable 24-character string such as ‘Wed Feb 06 14:07:14 2019’. Takes a time tuple as parameter
3 time.clock( )Returns the current CPU time. Return value is a floating-point number of seconds. Based on performance,  the value of time.clock is more useful than that of time.time().
4 time.ctime([secs])Similar to asctime(localtime(secs)) but without arguments is like asctime( )
5 time.gmtime([secs])Returns a time-tuple t with the UTC time. Accepts an instant expressed in seconds since the epoch as parameter. Note : t.tm_isdst is always 0
6 time.localtime([secs])Returns a time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on if DST applies to instant secs by local rules). Takes an instant expressed in seconds since the epoch  as parameter
7 time.mktime(tupletime)Returns a floating-point value with the instant expressed in seconds since the epoch. It takes an instant expressed as a time-tuple in local time and
8 time.sleep(secs)Use this to  suspends the calling thread for the specified seconds.
9 time.strftime(fmt[,tupletime])It returns a string representing the instant as given by string fmt. Accepts an instant expressed as a time-tuple in local time
10 time.strptime(str,fmt=’%a %b %d %H:%M:%S %Y’) Returns the instant in time-tuple format of a given string. Parses the given str according to format string fmt
11 time.time( )You used this to get the current time instant, a floating-point number of seconds since the epoch.
12 time.tzset()Resets the time conversion rules that is used by the library routines. The environment variable TZ shows how this is done.

 

6. The calendar Module

Functions related to calendar are provided by the calendar module. For example,  function to display a  complete calendar for a particular month.

By default, Monday is taken as the first day of the week. Then Sunday is regarded as the last day. However, the default behavior can be changed. To change is, use the calender.setfirstweekday() function.

A list of functions available in the calendar module is given below:

SN. Function and brief description
1 calendar.calendar(year,w=2,l=1,c=6)

Returns a multi-line string with a calendar for year year formatted into three columns separated by c spaces. w specifies 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.

2 calendar.firstweekday( )

Returns the current setting for the weekday that starts each week. By default, when calendar is first imported and used, it is 0, which means Monday.

3 calendar.isleap(year)

Returns True if the specified year is a leap year. Otherwise false

4 calendar.leapdays(y1,y2)

Gives the total number of leap days in the years within given  range(y1,y2).

5 calendar.month(year,month,w=2,l=1)

Returns a multi-line string with a calendar for the specified month of the year. One line per week plus two header lines. w is the number of character (width) of each date; each line has length 7*w+6. l is the number of lines for each week.

6 calendar.monthcalendar(year,month)

Returns a list of lists of ints. Each sublist denotes a week. Days that are outside the given month month of the specified year are set to 0; days within the month are set to their day-of-month, 1 and up.

7 calendar.monthrange(year,month)

Returns two values: code of the weekday for the first day of the specified month in year year and  t number of days in the month. Weekday codes are by default 0 (Monday) to 6 (Sunday); month numbers are 1 to 12. 1 for January, 2 for February etc

8 calendar.prcal(year,w=2,l=1,c=6)

Similar to print calendar.calendar(year,w,l,c).

9 calendar.prmonth(year,month,w=2,l=1)

Similar to print calendar.month(year,month,w,l).

10 calendar.setfirstweekday(weekday)

Used to set the first day of each week to weekday code weekday. Weekday codes are 0 (Monday) to 6 (Sunday) by dafault

11 calendar.timegm(tupletime)

Gives the inverse of time.gmtime: takes a time instant as parameter in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch.

12 calendar.weekday(year,month,day)

Returns the weekday code for the given date.  By default, weekday codes are 0 (Monday) to 6 (Sunday); month numbers are 1 (January) to 12 (December).