×

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 Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

FOO in Python

Python Programming Language: 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...

3 minutes read.

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python Skyline

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.

Python String isalpha() method

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

1 minute read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

What are the Purposes of Python?

Python is a high-level programming language that is simple to use and easy to write, and Python is a beginner-friendly programming language. A beginner often prefers to start with Python...

6 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

After Python, What Should I Learn

Python is a programming language used to create websites, software, and other projects. It is easy to code and easy to learn. After learning Python, there are many different directions...

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