×

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 Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent...

5 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 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.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.