Working with Date and Time in Python Applications

Markdown

View as Markdown

Date and time operations are commonly used in Python applications for scheduling, logging, reporting, automation, and data analysis. Python provides built-in modules that make it easy to work with dates, times, and timestamps.

This article explains how to create, format, manipulate, and compare dates and times in Python.

Understanding the datetime Module

Python provides the datetime module for working with dates and times.

Before using it, import the module:

from datetime import datetime

Displaying the Current Date and Time

Use the now() method to get the current date and time.

Example

Displaying Only the Current Date

Example

Displaying Only the Current Time

Example

Creating a Specific Date

You can create custom dates using the date() function.

Example

Creating a Specific Date and Time

Example

Formatting Dates and Times

The strftime() method formats dates and times into readable formats.

Example

Common Date Formatting Codes

Code

Description

Example

%d

Day

09

%m

Month

06

%Y

Year

2026

%H

Hour (24-hour)

15

%M

Minute

30

%S

Second

45

%A

Day Name

Tuesday

%B

Month Name

June

Formatting a Date with Month Name

Example

Converting a String to a Date

Use the strptime() method to convert text into a date object.

Example

Calculating Future Dates

The timedelta class allows you to add or subtract dates.

Example

Calculating Previous Dates

Example

Finding the Difference Between Two Dates

Example

Getting Individual Date Components

Example

 

Working with Time Components

Example

Comparing Dates

Example

 

Python's datetime module provides powerful tools for working with dates and times. You can retrieve the current date and time, format values for display, calculate future and past dates, compare dates, and process date-related information efficiently. These features are widely used in scheduling systems, reports, automation scripts, web applications, and business software.

 

Was this article helpful?

Still need help?

Contact us