Python Date Time

The datetime module provide the complete information date and time.

Below is the example to get date and time using datetime module.

datetime module is having below classes which get use most of the time:

  • datetime
  • date
  • time

datetime

datetime object is having datetime class to get date and time.

datetime.datetime.now() will give current date and time.

Example

OUTPUT

Set Custom datetime

using datetime object we can set date and time to use further.

datetime(year, month, date, hour, minute, second, microsecond)

OUTPUT:

Date

Using date time object we can find out the current date, month, year also as show in below example.

OUTPUT:

There are some other attributes from date class to get date, month and year separately.

OUTPUT:

Custom Date

Python allows us to create custom date object with user defined values.

OUTPUT
2022–09–28 00:00:00

Time

Using date time object we can find out the current time, hour, minutes, second and microsecond.

OUTPUT:

Date Format

Python provide us the capability to print data and time in specified format.

Below are the conventions we use to format the code.

Example

OUTPUT:

%P is use to print time having AM or PM.

OUTPUT:
Date Time = 12:19:04 PM

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0