A Comprehensive Guide for  Mastering Python's Date  & Time module

A Comprehensive Guide for Mastering Python's Date & Time module

Simplifying Date and Time Manipulation in Python Programming

Introduction

In this article, we'll learn in-depth about date and time in Python programming and practical examples. Understanding how date and time works is important due to its common usage when building applications.

💡
Already familiar with Python Date and Time or New to Python? Check out this comprehensive article on Python Path titled: A Comprehensive Guide for Understanding Directory in Python Programming

Date

Date is simply the unique description or address for each day. It consist of day, month, and year. For example: 01/02/2024 Date can be written in different format.
Such as:

  • Tuesday, February 2024

  • Tues., Feb., 2024

  • 01-02-2024;

  • February 1, 2024 etc.

This is a unique way to identify or refer to a day in the past, present or in the future.

Time

Is used to quantify or measure or define the duration of an event, intervals or happenings. The unit of measurement of time is in seconds, minutes, hours, and other units. There are variations to time representation due to different time zones. (tz). When building application it is important to put this into consideration.

Constants

The Python datetime module export the following constants that defines the minimum year, maximum year and utc:

from datetime import datetime

print(f"minmum year is: {datetime.min}")
# minmum year is: 0001-01-01 00:00:00

print(f"Largest year is: {datetime.max}")
# Largest year is: 9999-12-31 23:59:59.999999

print(f"UTC: {datetime.utcnow()}")
# UTC: 2024-02-02 13:37:12.628001

Date and Time in Python

datetime module in Python programming language provides classes which can be used to implement, manipulate and manage date and time functionalities in Python applications. Python Programming datetime values are objects. There are different types of classes in the datetime module in Python.

  • date

  • datetime

  • time

  • timedelta

  • tzinfo

  • timezone

Date

The date() method is used to manage date. The date class is imported from the datetime module to handle dates.

from datetime import date

today_date = date(2024, 2, 2)
print(f"Today date: {today_date}")
# Today date: 2024-02-02

Display current date

The date.today() is used to display the current date.

from datetime import date

today_date = date.today()
print(f"Current date: {today_date}")
# Current date: 2024-02-02

Accessing the attributes of date object

from datetime import date

today_date = date.today()
print(f"Current date: {today_date}")
# Current date: 2024-02-02
print(f"Current year: {today_date.year}")
#Current year: 2024
print(f"Current month: {today_date.month}")
# Current month: 2
print(f"Current day: {today_date.day}")
# Current day: 2

Datetime

The datetime class is used to handle full date and time object.

Display current Date and time

  • The datetime.now is used to get the current date and time.
from datetime import datetime

today_ts = datetime.now()
print(f"Today's date and time is: {today_ts}")
# Today's date and time is: 2024-02-02 03:58:19.784966

The output from the now() method contains: year-month-day hour:minute: second:microseconds

Accessing the attributes of the datetime

There are methods and attributes to access each part of the datetime object.

from datetime import datetime

today_ts = datetime.now()
print(f"Today's date and time is: {today_ts}")
# Today's date and time is: 2024-02-02 03:58:19.784966

print(f"The year part in this date: {today_ts} is:  {today_ts.year}")

print(f"The month part in this date: {today_ts} is:  {today_ts.month}")

print(f"The day part in this date: {today_ts} is:  {today_ts.day}")

print(f"The name of the weekday in this date: {today_ts} is:  {today_ts.strftime('%A')}")
  • Output

Create datetime object in Python

The datetime() method takes in three arguments (year, month, day) to create a date and time object. For example: the code below creates a date for 31st of January 2024.

from datetime import datetime

today_ts = datetime.now()
created_date_time_ts = datetime(2024, 1, 31)

print(f"Today's date and time is: {today_ts} but the created date is: {created_date_time_ts}")
# Today's date and time is: 2024-02-02 04:12:00.568671 but the created date is: 2024-01-31 00:00:00

The datetime() method also accept arguments to create hour, minute, second, microsecond.

Reading Python datetime in string format

The strftime() or isoformat() method can used to format the datetime or date object to a string format that is readable.

  • strftime()
from datetime import datetime

today_ts = datetime.now()
# #display the date time in a readable string
print(f"The month name of today's date and time ( {today_ts} ) is : {today_ts.strftime('%B')} ")
# The month name of today's date and time ( 2024-02-02 04:32:32.771660 ) is : February 

print(f"The month name in shorter form of today's date and time ( {today_ts} ) is : {today_ts.strftime('%b')} ")
#The month name in shorter form of today's date and time ( 2024-02-02 04:33:30.953912 ) is : Feb 

print(f"The month number form of today's date and time ( {today_ts} ) is : {today_ts.strftime('%m')} ")
# The month number form of today's date and time ( 2024-02-02 04:34:02.656355 ) is : 02

print(f"The weekday in shorter form of today's date and time ( {today_ts} ) is : {today_ts.strftime('%a')} ")
# The weekday in shorter form of today's date and time ( 2024-02-02 04:37:16.077069 ) is : Fri

print(f"The weekday of today's date and time ( {today_ts} ) is : {today_ts.strftime('%A')} ")
# The weekday of today's date and time ( 2024-02-02 04:37:16.077069 ) is : Friday

print(f"The day in number of today's date and time ( {today_ts} ) is : {today_ts.strftime('%d')} ")
# The day in number of today's date and time ( 2024-02-02 04:39:31.007871 ) is : 02
  • isoformat()
from datetime import datetime

python_time = datetime.now()
print(datetime.isoformat(python_time))
# 2024-02-02T05:24:38.339171
print(type(datetime.isoformat(python_time)))
# <class 'str'>

Other Python datetime format codes can be found in the python documentation.

Time

The time() method can take three arguments (hour, minute, seconds) or named parameters (hour=20) to form a time object as shown below:

from datetime import time

python_time = time(21, 14, 35)
print(f"Using time class: {python_time}")
# Using time class: 21:14:35

python_time_hr = time(hour=21)
print(f"Using a named argument: {python_time_hr}")
# Using a named argument: 21:00:00

#time(minute=21)

Accessing the attributes of time object

from datetime import time

python_time = time(21, 14, 35)

print(f"Time hour: {python_time.hour}")
# Time hour: 21

print(f"Time minutes: {python_time.minute}")
# Time minutes: 14

print(f"Time seconds: {python_time.second}")
# Time seconds: 35

print(f"Time microseconds: {time(21, 14, 35, 3345).microsecond}")
# Time microseconds: 3345

Converting timestamps to datetime object in Python

The datetime.fromtimestamp(arg) is used to handle timestamp conversion to datetime in Python programming.

from datetime import datetime

datetime_tz = datetime.fromtimestamp(2000259887)
print(f"Accessing timestamp datetime: {datetime_tz}")
# Accessing timestamp datetime: 2033-05-20 20:44:47

Timedelta

The timedelta() method can be used to add days, years, weeks etc to a date. For example let's add 50 days to the current date. This is handy when registration, job recruitment or functionalities in an application needs to be timed. timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0). All arguments in the timedelta method are optional and default to 0.

from datetime import datetime, timedelta


python_time = datetime.now()
days_ahead = python_time + timedelta(days=50)
print(f"The date after adding 50 days from now is: {days_ahead}")
# The date after adding 50 days from now is: 2024-03-23 05:21:36.665039

List of attributes and methods in Python datetime module

There are about 68 attributes and methods in the Python datetime module at the time of writing this article. Here's how to view the list of attributes and methods in the Python datetime module.

from datetime import datetime

today_ts = datetime.now()

# List attributes and methods in the datetime using dir 
attributes_and_methods = dir(today_ts)

print(f"total number of attributes and methods in the datetime module: {len(attributes_and_methods)}")
# total number of attributes and methods in the datetime module: 68

# Print the list of attributes and methods in Python datetime module
for item in attributes_and_methods:
    print(item)
💡
The same approach above can be employed to list the attributes and methods in time, date, timedelta.

Common Properties

According to Python documentation: The date, datetime, time, and timezone types share these common features:

  • Objects of these types are immutable (cannot be changed).

  • Objects of these types are hashable, meaning that they can be used as dictionary keys.

  • Objects of these types support efficient pickling via the pickle module.

Python datetime tzinfo

This serves as an abstract base class, indicating that direct instantiation of this class is not intended. Instead, create a subclass of tzinfo to encapsulate details about a specific time zone. Look up the documentation for more guide on tzinfo

Python datetime timezone

The timezone class is a specialized subclass of tzinfo, where each instance signifies a timezone characterized by a consistent offset from Coordinated Universal Time (UTC). Look up the documentation for more guide on timezone

Benefits of Date and Time in Applications

  • Database record can be managed with timestamps.

  • App activities can be defined to exist or happen within a specific date and time.

  • Transactions can be tracked using date and time.

  • Records can be sorted in ascending or descending other of their date and time entry.

  • Publications or other functionalities can be backdated. For example if one wants to manage publishing blog post in a chronological order by date and time this can be achieved by entering the record in a data store with the defined date and time.

  • This can be used to automatically update footer date in a new year.

Conclusion

Mastering date and time functionalities is necessary for developing applications. The date and time module in Python provides developers with attributes and methods to manipulate several it several types, such as date, time, datetime, timedelta, timzezone, tzinfo and the conversion from object to string. The basic examples in this article shows how to use datetime module types, methods and attributes and emphasizes the benefits of adding date and time functionalities to applications .

Find this helpful or resourceful? kindly share with others and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more comprehensive articles in Tech.

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!