×

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

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

Find key from value in dictionary python

Python: Python programming language is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a...

5 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.