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.

ExampleEdit & Run

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"))
Output:
2024/12/03 12:34:47[Finished in 0.012132512871176004s]

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:

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.

ExampleEdit & Run
#import the time class from the module
from datetime import time

#without any argument
t = time()
print(t)
Output:
00:00:00[Finished in 0.011902467114850879s]
ExampleEdit & Run

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)
Output:
time:  01:30:30hour:  1minute:  30second:  30[Finished in 0.011699203867465258s]

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.

ExampleEdit & Run
import datetime

print("minimum time: ", datetime.time.min)
print("maximum time: ", datetime.time.max)
Output:
minimum time:  00:00:00maximum time:  23:59:59.999999[Finished in 0.011596590979024768s]

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.

Syntax:
replace(hour = None, minute = None, second = None, microsecond = None, tzinfo = None)
ExampleEdit & Run
import datetime

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

t = t.replace(hour = 20, second = 8)
print(t)
Output:
18:30:1020:30:08[Finished in 0.011216833023354411s]

The strftime() method

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

Syntax:
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

ExampleEdit & Run
import datetime

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

print("default: ", t)

print("custom", t.strftime("%H-%M-%S"))
Output:
default:  19:30:00custom 19-30-00[Finished in 0.011623984901234508s]
ExampleEdit & Run

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"))
Output:
A builtin module you are using is currently not supported.

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.

Syntax:
date(year, month, day)

All the three values are required when instantiating date objects.

ExampleEdit & Run
import datetime

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

print(d)
Output:
2023-08-14[Finished in 0.011345637030899525s]

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

ExampleEdit & Run

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())
Output:
2024-12-03year:  2024month:  12day:  3weekday:  1[Finished in 0.01140452385880053s]

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

ExampleEdit & Run

print the valid date range

import datetime

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

#the maxmum possible date
print(datetime.date.max)
Output:
0001-01-019999-12-31[Finished in 0.011888028122484684s]

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.

Syntax:
replace(year = None, month = None, day = None)
ExampleEdit & Run
import datetime

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

print(d, end = '\n')

d2 = d.replace(year = 2024)
print(d2)
Output:
2023-08-102024-08-10[Finished in 0.011600146070122719s]
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.

Syntax:
fromtimestamp(timestamp)
ExampleEdit & Run
import datetime

piday_timestamp = 1521024000

print(datetime.date.fromtimestamp(piday_timestamp))
Output:
2018-03-14[Finished in 0.011324835941195488s]
date.isoformat()

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

ExampleEdit & Run
import datetime

today = datetime.date.today()

print(today.isoformat())
Output:
2024-12-03[Finished in 0.01152732502669096s]
date.ctime()

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

Syntax:
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.

ExampleEdit & Run
import datetime

today = datetime.date.today()

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

#with ctime formatting
print(today.ctime())
Output:
2024-12-03Tue Dec  3 00:00:00 2024[Finished in 0.011211815988644958s]
date.strftime()

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

Syntax:
strftime(format)

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

ExampleEdit & Run
import datetime

today = datetime.date.today()

#without formating
print(today)

#With formating
print(today.strftime("%b %d %Y"))
Output:
2024-12-03Dec 03 2024[Finished in 0.01168726896867156s]

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:

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. 

ExampleEdit & Run

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)
Output:
2024-12-03 13:30:23[Finished in 0.011547135887667537s]

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.

ExampleEdit & Run
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)

Output:
2024-12-03 12:34:47.327010Tue Dec  3 12:34:47 2024year:  2024month:  12day:  3hour:  12minute:  34second:  47[Finished in 0.011523279128596187s]

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.

ExampleEdit & Run

the today() method

import datetime

print(datetime.datetime.today())
Output:
2024-12-03 12:34:47.340007[Finished in 0.011543239932507277s]
ExampleEdit & Run

The  utcnow() method

import datetime

print(datetime.datetime.utcnow())
Output:
2024-12-03 09:34:47.352571[Finished in 0.011541816871613264s]

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.

ExampleEdit & Run
import datetime

print(datetime.datetime.now())
Output:
2024-12-03 12:34:47.364992[Finished in 0.011358079966157675s]

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.

ExampleEdit & Run

using the ctime() method

import datetime

now = datetime.datetime.now()

print(now.ctime())
Output:
Tue Dec  3 12:34:47 2024[Finished in 0.011886553140357137s]

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

ExampleEdit & Run

formatting a datetime using the strftime method

import datetime

today = datetime.datetime.now()

#With formating
print(today.strftime("%b %d %Y %H:%M:%S"))
Output:
Dec 03 2024 12:34:47[Finished in 0.011712450068444014s]

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.

Syntax:
strptime(datetime_string, format)
ExampleEdit & Run
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)
Output:
2023-08-15 00:52:39 year:  2023month:  8day:  15hour:  0minute:  52second:  39[Finished in 0.019928212044760585s]

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.