Python Datetime

Python 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

This 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan