The datetime module in the standard library provide essential classes and functions for representing and manipulating dates and time. It shares some functionality with the time module. Both provide ways to access and manipulate date and time values, with the datetime module offering more advanced features and capabilities.

The module contains several classes for working with dates and time. These classes can be summarized as:

  • time: Represents a single time, including hour, minute, second,  microsecond , and tzinfo.
  • date: Represents a single date, including year, month, and day.
  • datetime: This class combines the features of the date and time classes into a single class.
  • timedelta: This class represents the difference between two datetime objects.
  • tzinfo: This abstract class is used to define time zones and daylight saving time.
  • timezone: This class is used to create concrete time zone objects.

We will have to import the datetime module or the specific required assets in our programs before use.

Using the datetime module

#import the datetime class from the module
from datetime import datetime

now = datetime.now()

print(now.strftime("%Y/%m/%d %H:%M:%S"))

Working with Time - the time class

The datetime module defines the time class which represents time values without  date information.. In this class, time objects are represented using 5 parameters i.e  hour, minute, second, microsecond and tzinfo. We can use these attributes to manipulate, display, or compare time values. To instantiate a time object we pass the necessary arguments to the constructor using the following syntax:

time(hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None )

All the five arguments are optional, they all default to 0 except the tzinfo which defaults to None.

#import the time class from the module
from datetime import time

#without any argument
t = time()
print(t)

With some arguments given

from datetime import time

t = time(1, 30, 30)

print("time: ", t, end = '\n')

#Accessing individual components of a time object
print('hour: ', t.hour)
print('minute: ', t.minute)
print('second: ', t.second)

minimum and maximum time values

The  time class defines the min and max attributes which represent the smallest and largest time values, respectively. The two attributes can be used to  determine the valid range of values for time objects.

import datetime

print("minimum time: ", datetime.time.min)
print("maximum time: ", datetime.time.max)

The replace() method

We can use the replace() method create a new time object based on the values of the current time . The method takes any of the 5 parameters - hour, minute, second, microsecond, tzinfo.

replace(hour = None, minute = None, second = None, microsecond = None, tzinfo = None)
import datetime

t = datetime.time(18, 30, 10)
print(t)

t = t.replace(hour = 20, second = 8)
print(t)

The strftime() method

The strftime() method allows us to customize the way  time is displayed.

strftime(format = "%H:%M:%S")

The  format parameter should be  a string with placeholders representing how the time should be formatted. By default, the "%H:%M:%S" format is used, this is the reason why time is displayed as  hh:mm:ss

import datetime

t = datetime.time(19, 30, 00)

print("default: ", t)

print("custom", t.strftime("%H-%M-%S"))

Showing time in a 12 hour system

import datetime

t = datetime.time(19, 30, 00)

#The %I formatter makes the time to be displayed in 12-hour clock-system
print(t.strftime("%I-%M-%S"))

The methods of the time class can be summarized as:

Method Usage
isoformat() Returns a string representation of the time in ISO 8601 format.
strftime() Formats the time using the given format string.
replace() Creates a new time object from the current with some values replaced.
dst() Returns 1 if Daylight Saving Time (DST) is in effect, 0 otherwise. Only works if tzinfo is not None.
utcoffset() Returns the local timezone’s offset from UTC. Only works if tzinfo is not None.
tzname() The name of the timezone if tzinfo is not None.

Working with dates - the date class

The date class is used to represent calendar dates without time information. A date object is created using the class constructor which takes parameters for year, month and date.

date(year, month, day)

All the three values are required when instantiating date objects.

import datetime

d = datetime.date(2023, 8, 14)

print(d)

If you want current date, you can simply use the  today() class method.

Get today's date

import datetime

today = datetime.date.today()

print(today, end = '\n')

#some date attributes
print('year: ', today.year)
print('month: ', today.month)
print('day: ', today.day)
print('weekday: ', today.weekday())

We can check the smallest and the largest valid dates using the min and max, class attributes.

print the valid date range

import datetime

#the minimum possible date
print(datetime.date.min)

#the maxmum possible date
print(datetime.date.max)

Date methods

The date class defines some useful methods. We have already seen one of the methods, i.e today() , other methods includes:

date.replace()

This method creates a new date object based on the values of the current date object.

replace(year = None, month = None, day = None)
import datetime

d = datetime.date(2023, 8, 10)

print(d, end = '\n')

d2 = d.replace(year = 2024)
print(d2)
date. fromtimestamp()

If you are familiar withe the time module, you might already be familiar with how timestamps work. In a nutshell, a timestamp refers the number of seconds  since  the epoch(January 1, 1970) up to a certain date.

The fromtimestamp() method creates a date objects from a given  timestamp.

fromtimestamp(timestamp)
import datetime

piday_timestamp = 1521024000

print(datetime.date.fromtimestamp(piday_timestamp))
date.isoformat()

This method converts a date object into a ISO 8601 formatted string.  

import datetime

today = datetime.date.today()

print(today.isoformat())
date.ctime()

This method is used to format a date object into the "%a %b %d %H:%M:%S %Y"  format.

ctime()

The default format is "%a %b %d %H:%M:%S %Y"  meaning that, with this method,  a date is represented as for example Sunday, July 28th, 11:35:03, 2023.

import datetime

today = datetime.date.today()

#without ctime formating
print(today, end = '\n')

#with ctime formatting
print(today.ctime())
date.strftime()

This method allows us to customize how a date object will look using custom formats.

strftime(format)

The format is a string containing the relevant placeholders representing how the date should be displayed.

import datetime

today = datetime.date.today()

#without formating
print(today)

#With formating
print(today.strftime("%b %d %Y"))

All the methods of the date class are summarized by the following table.

Method

Usage

ctime() Returns a string representing the date in a human readable form.
fromisocalendar() Returns a date corresponding to the ISO calendar
fromisoformat() Returns a date object from the string representation of the date
fromordinal() Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1
fromtimestamp() Creates a date object from a given timestamp
isocalendar() Returns a tuple year, week, and weekday
isoformat() Used to represent a date object as a string in ISO 8601 format.
isoweekday() Returns the day of the week as an integer with Monday as 1.
replace() Creates a new date object from the values of the current date replaced with the arguments values.
strftime() Returns a string representation of the date with the given format
timetuple() Converts the current date into time.struct_time object.
today() Returns the current date in local time
toordinal() Return the proleptic Gregorian ordinal of the date.
weekday() Returns the day of the week as integer with Monday as 0. 

Dates and Time combined - The datetime class

The datetime class is used to hold values consisting of both date and time components.

Note: the class shares the same name with the module.

To instantiate objects of this class, we use the following syntax:

datetime(year, month, day, hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None)

The date arguments are required while the time arguments are optional as shown in the above syntax.

This class'  functionality is simply the combination of the date and the time classes. It is actually possible to instantiate a datetime objects from two seperate date and time objects using the combine method. 

Combine a date and a time object to create a datetime.

import datetime

d = datetime.date.today()

t = datetime.time(13, 30, 23)

#Combine the date and the time
dt = datetime.datetime.combine(d, t)

print(dt)

The current date and time

One of the most used methods of the datetime classes is the now() method, this method returns the current local time including date and time components.

import datetime

current = datetime.datetime.now()

#basic
print(current)

#Formatted
print(current.ctime(), end = '\n\n')

#date attributes
print('year: ', current.year)
print('month: ', current.month)
print('day: ', current.day)

#some time attributes
print('hour: ', current.hour)
print('minute: ', current.minute)
print('second: ', current.second)

Other almost similar to the now() method are the today() and the utcnow() methods. In most cases the three methods usually return the same value. Except that the utcnow() method returns timezone aware datetime objects while the other two returns timezone naive datetime objects.

the today() method

import datetime

print(datetime.datetime.today())

The  utcnow() method

import datetime

print(datetime.datetime.utcnow())

Formatting and Parsing

By default, the datetime objects are formatted using ISO 8601 format.(YYYY-MM-DDTHH:MM:SS.), for example 2023-05-19T14:45:53, which represents May 19th, 2020 at 2:45:53 PM. This format allows for the consistent formatting of datetime objects to be displayed and transferred across different systems, as long as they adhere to the standard.

import datetime

print(datetime.datetime.now())

We can change the default format using the various methods meant for this purpose. The most basic of them is the ctime(), which converts a datetime into  a string in the  "Month DD YYYY HH:MM:SS" format.

using the ctime() method

import datetime

now = datetime.datetime.now()

print(now.ctime())

The strftime() method allows us to customize the format.

formatting a datetime using the strftime method

import datetime

today = datetime.datetime.now()

#With formating
print(today.strftime("%b %d %Y %H:%M:%S"))

Create a datetime object from a formatted string

If a string contains a valid datetime values, we can use the strptime() method to create a datetime object from the strings.

strptime(datetime_string, format)
import datetime

datetime_string = "Aug 15 2023 00:52:39"

my_datetime = datetime.datetime.strptime(datetime_string, "%b %d %Y %H:%M:%S")
print(my_datetime, '\n')

print('year: ', my_datetime.year)
print('month: ', my_datetime.month)
print('day: ', my_datetime.day)
print('hour: ', my_datetime.hour)
print('minute: ', my_datetime.minute)
print('second: ', my_datetime.second)

Note: The methods of the datetime class and its objects are similar to those of date and time classes combined, with the adjustments done where necessary.