blog image

Python's datetime Module Explained

February 16, 20245 min read

The datetime module in Python is a comprehensive library designed for manipulating dates and times. This module encompasses a range of classes that allow you to represent and modify dates and times, in addition to offering functionality for formatting and parsing them in various ways.

Getting the Current Date and Time

To begin, let's see how you can fetch the current date and time:

import datetime

# Fetching current date and time
now = datetime.datetime.now()

print(now)

When you run this code, it outputs the current date and time, such as "2022-12-27 08:26:49.219717".

By importing the datetime module, we gain access to several classes within it, including the essential datetime class. The now() method is used here to generate an object containing the current local date and time.

Fetching the Current Date

Moving on to obtaining just the current date:

import datetime

# Fetching the current date
today = datetime.date.today()

print(today)

This snippet will display the current date in the format "2022-12-27", achieved through the today() method from the date class, which returns an object with the current local date.

Exploring datetime Module Attributes

You can explore all attributes and methods of the datetime module using the dir() function:

import datetime

print(dir(datetime))

This will list all the available attributes, including classes like datetime.datetime, datetime.date, datetime.time, and datetime.timedelta, which are crucial for handling dates and times.

Creating Date Objects

Let's create a specific date:

import datetime

date_example = datetime.date(2022, 12, 25)
print(date_example)

In this example, we use the date() constructor from the date class to create a date object. This constructor requires three arguments: year, month, and day.

Importing Specific Classes

You can also import specific classes from the datetime module:

from datetime import date

specific_date = date(2022, 12, 25)
print(specific_date)

This code snippet does the same as before but imports only the date class for simplicity.

Using today() to Obtain the Current Date

To get the current date in another way:

from datetime import date

# Using today() to get the current date
current_date = date.today()

print("Today's date =", current_date)

This method gives you the current date, such as "2022-12-27".

Creating Date from Timestamp

You can also create a date object from a UNIX timestamp:

from datetime import date

timestamp_example = date.fromtimestamp(1326244364)
print("Date from timestamp =", timestamp_example)

This converts a UNIX timestamp into a readable date format.

Extracting Components of Today's Date

Extracting specific components like the year, month, and day:

from datetime import date

today = date.today()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

This snippet displays the current year, month, and day.

The datetime.time Class

Representing specific times is also straightforward:

from datetime import time

time_a = time()
print(time_a)

time_b = time(11, 34, 56)
print(time_b)

time_c = time(hour=11, minute=34, second=56)
print(time_c)

time_d = time(11, 34, 56, 234566)
print(time_d)

This example shows how to create time objects with various levels of precision.

Printing Time Components

To print individual components like hour and minute:

from datetime import time

sample_time = time(11, 34, 56)

print("Hour:", sample_time.hour)
print("Minute:", sample_time.minute)
print("Second:", sample_time.second)
print("Microsecond:", sample_time.microsecond)

The datetime.datetime Class

Combining date and time into one object:

from datetime import datetime

datetime_a = datetime(2022, 12, 28)
print(datetime_a)

datetime_b = datetime(2022, 12, 28, 23, 55, 59, 342380)
print(datetime_b)

This demonstrates how to create datetime objects with both date and time.

Displaying Components of a datetime Object

Extracting and printing components from a datetime object:

from datetime import datetime

datetime_example = datetime(2022, 12, 28, 23, 55, 59, 342380)

print("Year:", datetime_example.year)
print("Month:", datetime_example.month)
print("Hour:", datetime_example.hour)
print("Minute:", datetime_example.minute)
print

("Timestamp:", datetime_example.timestamp())

Working with Time Durations

Using the timedelta class for durations:

from datetime import datetime, date

date1 = date(year=2018, month=7, day=12)
date2 = date(year=2017, month=12, day=23)

duration = date1 - date2

print("Duration:", duration)

datetime1 = datetime(year=2018, month=7, day=12, hour=7, minute=9, second=33)
datetime2 = datetime(year=2019, month=6, day=10, hour=5, minute=55, second=13)

duration_dt = datetime1 - datetime2
print("Duration with time:", duration_dt)

This calculates the duration between two dates or datetime objects.

Difference Between Two timedelta Objects

Calculating differences between durations:

from datetime import timedelta

timedelta1 = timedelta(weeks=2, days=5, hours=1, seconds=33)
timedelta2 = timedelta(days=4, hours=11, minutes=4, seconds=54)

difference = timedelta1 - timedelta2

print("Difference between durations:", difference)

Duration in Seconds

To get the total seconds of a timedelta:

from datetime import timedelta

timedelta_example = timedelta(days=5, hours=1, seconds=33, microseconds=233423)
print("Total seconds in duration:", timedelta_example.total_seconds())

Formatting Dates and Times

Python allows for formatting dates and times in various ways using the strftime() method:

from datetime import datetime

now = datetime.now()

formatted_time = now.strftime("%H:%M:%S")
print("Formatted time:", formatted_time)

formatted_date_time1 = now.strftime("%m/%d/%Y, %H:%M:%S")
print("Formatted date and time (US):", formatted_date_time1)

formatted_date_time2 = now.strftime("%d/%m/%Y, %H:%M:%S")
print("Formatted date and time (UK):", formatted_date_time2)

Parsing String to datetime

import datetime

date_str = "25 December, 2022"
print("String representation:", date_str)

# Converting string to datetime object
date_obj = datetime.datetime.strptime(date_str, "%d %B, %Y")
print("Converted to datetime:", date_obj)

This example demonstrates how to convert a string to a datetime object using the strptime() method, which requires the string format to match the specified pattern.

Handling Timezones

For projects requiring timezone-aware dates and times, consider utilizing the pytz module for comprehensive timezone support:

from datetime import datetime
import pytz

local_time = datetime.now()
print("Local time:", local_time.strftime("%m/%d/%Y, %H:%M:%S"))

# New York timezone
ny_timezone = pytz.timezone('America/New_York')
datetime_ny = datetime.now(ny_timezone)
print("New York time:", datetime_ny.strftime("%m/%d/%Y, %H:%M:%S"))

# London timezone
london_timezone = pytz.timezone('Europe/London')
datetime_london = datetime.now(london_timezone)
print("London time:", datetime_london.strftime("%m/%d/%Y, %H:%M:%S"))

This snippet illustrates how to work with timezones to obtain the current time in different cities around the world, ensuring your Python applications can handle global time variations efficiently.

Here's a table summarizing common string formatting directives used with Python's datetime.strftime() method for formatting date and time objects into strings:

Custom HTML/CSS/JAVASCRIPT

These directives can be combined in various ways to format dates and times into strings as per your requirements. For example, to format a datetime object into a string like "Wednesday, April 5, 2023, 14:30", you would use the format string %A, %B %d, %Y, %H:%M.

Conclusion

The datetime module in Python is a versatile library for handling dates and times, from simple tasks like getting the current date and time to more complex operations involving time zones and formatting. By leveraging the classes and methods provided by this module, you can effectively manage date and time data in your Python projects, making your applications more dynamic and time-aware.

blog author image

sunil s

Quant Developer & Mentor

Back to Blog