Python Dates

Working with dates and times is essential for many applications. Python provides the datetime module to handle date and time operations. This module supplies classes for manipulating dates and times in both simple and complex ways.

Importing the datetime Module

Before working with dates, you need to import the datetime module.

import datetime

Example 1: Getting the Current Date and Time

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

# Getting current date and time
import datetime
now = datetime.datetime.now()
print("Current Date and Time:", now)

Output (The output will show the current date and time)

Current Date and Time: 2023-10-05 12:34:56.789123

Example 2: Creating a Specific Date

Create a date object representing India's Independence Day.

# Creating a specific date
import datetime
independence_day = datetime.date(1947, 8, 15)
print("India's Independence Day:", independence_day)

India's Independence Day: 1947-08-15

Example 3: Formatting Dates

Format a date object into a readable string using strftime().

# Formatting dates
import datetime
now = datetime.datetime.now()
formatted_date = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted Date:", formatted_date)

Output Formatted date and time

Formatted Date: 05-10-2023 12:34:56

Example 4: Parsing Dates

Convert a string into a date object using strptime().

# Parsing dates from strings
import datetime
date_string = "26/01/1950"
parsed_date = datetime.datetime.strptime(date_string, "%d/%m/%Y")
print("Parsed Date:", parsed_date)

Parsed Date: 1950-01-26 00:00:00

Example 5: Date Arithmetic

Calculate the number of days between two dates.

# Calculating difference between dates
import datetime
start_date = datetime.date(2023, 1, 1)
end_date = datetime.date(2023, 12, 31)
delta = end_date - start_date
print("Days between dates:", delta.days)

Days between dates: 364

Example 6: Adding Time Delta

Add 10 days to the current date.

# Adding timedelta
import datetime
now = datetime.datetime.now()
future_date = now + datetime.timedelta(days=10)
print("Date after 10 days:", future_date.strftime("%d-%m-%Y"))

Date after 10 days: 15-10-2023

Example 7: Working with Timezones

Use the pytz library to handle timezones.

# Working with timezones
import datetime
import pytz
india_tz = pytz.timezone('Asia/Kolkata')
now_in_india = datetime.datetime.now(india_tz)
print("Current Time in India:", now_in_india.strftime("%Y-%m-%d %H:%M:%S"))

Note: You need to install pytz using pip install pytz.

Current Time in India: 2023-10-05 18:04:56

Example 8: Comparing Dates

Check if a date is in the past, present, or future.

# Comparing dates
import datetime
event_date = datetime.date(2023, 10, 10)
today = datetime.date.today()
if event_date > today:
    print("The event is in the future.")
elif event_date == today:
    print("The event is today.")
else:
    print("The event has passed.")

The event is in the future.

Example 9: Measuring Execution Time

Calculate how long it takes to execute a piece of code.

# Measuring execution time
import datetime
def long_computation():
    total = 0
    for i in range(1, 1000000):
        total += i

start_time = datetime.datetime.now()
long_computation()
end_time = datetime.datetime.now()
execution_time = end_time - start_time
print("Execution Time:", execution_time)

Execution Time: 0:00:00.089123

Example 10: Handling Date Exceptions

Use try-except blocks to handle invalid date inputs.

# Handling date exceptions
import datetime
try:
    invalid_date = datetime.datetime.strptime("31-02-2023", "%d-%m-%Y")
except ValueError as e:
    print("Error:", e)

Error: day is out of range for month

Formatting Codes Reference

Common formatting codes used with strftime() and strptime():

  • %Y - Year with century (e.g., 2023)
  • %m - Month as a zero-padded decimal (e.g., 01 to 12)
  • %d - Day of the month (e.g., 01 to 31)
  • %H - Hour in 24-hour clock (e.g., 00 to 23)
  • %M - Minute (e.g., 00 to 59)
  • %S - Second (e.g., 00 to 59)
  • %A - Weekday name (e.g., Monday)
  • %B - Month name (e.g., January)

Example 11: Displaying Date in Different Formats

Show the current date in various formats.

# Displaying date in different formats
import datetime
now = datetime.datetime.now()
formats = [
    "%d/%m/%Y",
    "%m-%d-%Y",
    "%B %d, %Y",
    "%A, %B %d, %Y",
    "%Y-%m-%d %H:%M:%S"
]
for fmt in formats:
    print(now.strftime(fmt))

05/10/2023

10-05-2023

October 05, 2023

Thursday, October 05, 2023

2023-10-05 12:34:56

Example 12: Using dateutil Module

Parse dates in various formats using the dateutil module.

# Using dateutil parser
from dateutil import parser
date_strings = ["15th of August, 1947", "2023-10-05", "Oct 5, 2023"]
for date_str in date_strings:
    parsed_date = parser.parse(date_str)
    print(parsed_date)

Note: You need to install python-dateutil using pip install python-dateutil.

1947-08-15 00:00:00

2023-10-05 00:00:00

2023-10-05 00:00:00

Example 13: Converting Timestamp to Date

Convert a Unix timestamp to a readable date.

# Converting timestamp to date
import datetime
timestamp = 1609459200  # January 1, 2021
date = datetime.datetime.fromtimestamp(timestamp)
print("Date:", date)

Date: 2021-01-01 00:00:00

Example 14: Generating a Date Range

Create a list of dates between two dates.

# Generating a date range
import datetime
start_date = datetime.date(2023, 10, 1)
end_date = datetime.date(2023, 10, 5)
delta = datetime.timedelta(days=1)
current_date = start_date
while current_date <= end_date:
    print(current_date)
    current_date += delta

2023-10-01

2023-10-02

2023-10-03

2023-10-04

2023-10-05

Example 15: Working with calendar Module

Display a month's calendar.

# Displaying a month's calendar
import calendar
year = 2023
month = 10
print(calendar.month(year, month))
    October 2023
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Explanation: The datetime module is powerful and versatile for handling dates and times. By mastering its functions and classes, you can perform a wide range of date and time operations in your Python programs.