Introduction to Python Date-Time module with Practical Examples

In this article you will learn about Python date-time.

Python Date-Time – before moving ahead, let’s know a little bit about Python Module

Python Date – Import module named datetime, to know the date-time and work with the objects related to date.

Example 1- Import the module named datetime to know current date.

import datetime
x = datetime.datetime.now()

print(x)
Python date-time

Explanation In the above example, module datetime retuned the current date and in respective format.

Note:  The date time will contain year, month, day, hour, minute, second, and microsecond.

Note:  The module date time has various ways to execute date and time.

Let’s start with those ways of executing date-time.

Example 2- Import datetime to return year, month, day.

import datetime
x = datetime.datetime.now()
 
print(x.year)
print(x.month)
print(x.day) 
Python date-time

Explanation In the above example, it returned date in specific format.

Create datetime Object – Use class (constructor) of module datetime. class of datetime takes three parameters which includes year, month, day.

Example 3- Import datetime module to create a date object.

import datetime
z = datetime.datetime(2020, 6, 26)

print (z)
Python date-time

Explanation In the above example, used class date time constructor that returned date in specific format.

Note: The class datetime() also takes more argument but they are optional, it includes hour, minute, second, microsecond, tzone. It has a default value of 0 , and None for timezone.

The strftime() Method – The datetime object has a method strftime() to format into strings. It takes one parameter – format, to specify the format of the returned string.

Example 4- It returns the name of the month.

import datetime
x = datetime.datetime( 2001,1,26)

print (x.strftime( "%B" ))
Python date-time

Explanation – In the above example, used method strftime() to set the format of date.

If you find anything incorrect in the above-discussed topic and have any further questions, please comment down below.

Like us on

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on