×

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is not a separate data type in Python, but we can work with the date objects by importing the module named with datetime, time, and calendar.

The datetime module permits us to generate the custom date objects to perform various operations on dates like the comparison, formatting, etc.

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

 Get the current time

The date module provides the localtime() function which is used to get the current time tuple. The example is following:

import time
z = time.localtime(time.time())
print(z)

Output:

time.struct_time(tm_year=2019, tm_mon=9, tm_mday=15,
tm_hour=17, tm_min=48, tm_sec=58, tm_wday=6, tm_y
day=258, tm_isdst=0)

The time() function

The time() function returns the total number of tick spent since 12 AM, 1st January. A tick can be considered as the smallest unit of the time. The time instants are counted since 12AM, 1st January.

import time
# prints the number of ticks spend since 12 AM, 1st January 1970
print(time.time())

Output:

1568609547.41062

Time Tuple

Index Attribute Values
0 Year 4 digit
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

Get formatted time

The time module provides the asctime() function, which is used to format the time. It returns the formatted time for the time tuple which is passed in the asctime().

import time
print(time.asctime(time.localtime(time.time())))

Output:

Mon Sep 16 12:47:17 2019

Sleep time

The sleep() method is used to stop the execution of the python script for a  given amount of time. Consider the following example:

import time
for i in range(0,5):
print(i)
# each element will be printed after 2 seconds
time.sleep(2)

Output:

 0
 1
 2
 3
 4 

Create date object

The date objects can be created by using datetime constructor and by passing the desire data for which the date objects are to be created. Consider the following example:

import datetime
#returns the datetime object for the specified date
print(datetime.datetime(2018,12,10))

Output

2018-12-10 00:00:00

Get current date and time

The now() returns the current date and time. Let’s consider the following example:

import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)

Output:

2019-09-16 11:54:49.696754

Inside datetime

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

import datetime
print(dir(datetime))

Output:

['MAXYEAR',
'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI',
'time', 'timedelta', 'timezone', 'tzinfo']

Get current date

import datetime
date_object = datetime.datetime.now()
print(date_object)

Output:

2019-09-16

In the above program, we have used today() method to define the date class to get a date object containing the current local date.

Comparison of two dates

The two dates can be compared by using comparison operator like >>=, < and <=. Consider the following example.

 from datetime import datetime as dt
 #Compares the time. If the time is in between 8AM and 4PM, then it prints working hours  otherwise it prints fun hours
 if dt(dt.now().year,dt.now().month,dt.now().day,8)



Output

Working hours....

Difference between two dates and time

from datetime import datetime, date
t1 = date(year =2019, month = 7, day = 12, hour = 7, minute = 9, second = 33 )
t2 = date(year = 2018, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t3 = t1-t2
print("t3=",t3)
t4 = datetime(year = 2017, month = 7, day = 12, hour = 7, minute = 9, second =13)
t5 = datetime(year = 2018, month = 6, day = 10, hour = 5, minute = 55, second =33)
t6 = t4-t5
print("t6=",t6)

Output:

t3= 397 days,0:00:00
t6= -333 days, 1:13:40 

The calendar module

Python provides a calendar object that contains various method to work with the calenders.

import calendar
cal =   calendar.month(2018,11)
print(cal)

The above code will generate the calendar of the year 2017 month of November

Output

python-date-and-time

Printing the calendar of the whole year

import calendar
year = 2017
# display the calendar
print(calendar.calendar(yy))

Output

python-date-and-time-1

Related Topics

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.