Post

DateTime Module - The Most Frequently Used Module Throughout Programming

This module alone is used that much that it needs its own unit. We may not encounter this function often when using systems that have been designed, but there are elements within the system that utilise it. Consider tasks such as saving information, uploading data, or recording general timestamp information. We need to be able to collect and log all that information. This is how we do it and use it.

DateTime Module - The Most Frequently Used Module Throughout Programming

I’ve revised over the topic of modules on an earlier post1, and in today’s topic, we go into detail on one module in particular - DateTime. It’s not often that we would come across this function in systems, but every system uses this function, whether it is programmed using Python or not. It’s vital to know how to use this when it comes to Python programming as we begin to code.

The DateTime module in Python allows you as a developer to extract real-time Date and Time results. This could be used for numerous things, like logs and timestamps. The uses of these aren’t limited, and they are vast; it just depends on your own creativity.


Using DateTime Module

This is how we would import the module and then have all the functions available within it listed to us.

1
2
3
4
import datetime

print(dir(datetime))
# ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

Of course, we won’t sit and go through each of the functions, but you can have a read through of them on the official Python website/documentation.

Link: Official Python Documentation - DateTime Module

Having a basic read over will inform you of all the tools available in Python and what we can do.

How To Use DateTime

Now that we have a low-level understanding of the DateTime module, let’s think about the ways we can use it. For now, we’ll focus on the retrieval of real-time date and time.

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
32
33
34
import datetime # or
from datetime import datetime # or
from datetime import *

now = datetime.now()
print(now)          # 2026-01-02 16:54:04.901574 - prints off date time including milliseconds.

day = now.day
print(day)          # 2

month = now.month
print(month)        # 1

year = now.year
print(year)         # 2026

hour = now.hour
print(hour)         # 16

minute = now.minute
print(minute)       # 54

second = now.second
print(second)       # 04

microsecond = now.microsecond
print(microsecond)   # .901574

# I wanted to include here that on the Python documentation, you will find that the datetime feature brings back microseconds as default, but we do have milliseconds. You can identify the two by knowing how many decimal figures there are; a microsecond has 6 and a millisecond has 3.

timestamp = now.timestamp()
print(timestamp) # 1767200044.901574

# This function is also known as 'UNIX timestamp', which retrieves the number of seconds elapsed from the 1st Jan 1970 UTC (Coordinated Universal Time)

This example has been able to use the datetime module to retrieve real world time, then its been able to store that into a variable named now. From that variable, we have called on the separate parts of that using keywords and brought them back as a singular result and placed them in their own variables.

Before I go on ahead and explain strftime I want to take the opportunity to mention that we are also able to store our own date & time using the correct formats as an input. Think about creating a variable that will hold a specific date and time that you insert.

1
2
3
4
from datetime import *

yesterday = datetime(2026, 1, 2, 19, 0, 0)
print(yesterday) # 2026-01-02 19:00:00

String Formats with DateTime or strftime

In one of my earlier posts, I made an attempt at explaining string formats in Python and how we can use them. With the DateTime module, we can do something similar.

When we use string formatting, we usually, in the new method, call on the f-string method, which enables us access to access those features. When it comes to using strftime, we call on the .strftime() function and insert all the values we require inside the parentheses.

I have used ChatGPT and the contents from the original course to build the table below, which should be a little more descriptive and helpful for beginners like myself.

DirectiveWhat it Means (Plain English)Example OutputHow You Might Use It
%aShort name of the weekdaySatDisplay a short day name in logs or UI
%AFull name of the weekdaySaturdayShow full readable weekday
%wDay of the week as a number (0 = Sunday, 6 = Saturday)6Useful for calculations or logic
%dDay of the month (always 2 digits)03Show the day portion of a date
%bShort month nameJanCompact month display
%BFull month nameJanuaryUser-friendly month display
%mMonth as a number (01–12)01Sorting or numeric comparisons
%yYear without century (last two digits)26Short year format
%YFull year2026Standard year display
%HHour (24-hour clock, 00–23)16Military/24-hour time
%IHour (12-hour clock, 01–12)04Used with AM/PM
%pAM or PMPMIndicates time of day
%MMinutes (00–59)54Time formatting
%SSeconds (00–59)04Precise time display
%fMicroseconds (millionths of a second)901574High-precision timestamps
%zUTC offset (difference from UTC time)+0100Timezone offsets
%ZTimezone nameGMTDisplay timezone
%jDay of the year (001–366)365Tracking yearly progress
%UWeek number of the year (Sunday as first day)52Weekly reports (US style)
%WWeek number of the year (Monday as first day)52Weekly reports (ISO style)
%cFull local date and timeSat Jan 3 16:54:04 2026Quick readable timestamp
%xLocal date only03/01/26Date display only
%XLocal time only16:54:04Time display only
%%A literal percent sign%Escape % in strings

Table source: datetime strftime directives - 30 Days of Python by Asabeneh

Example Use:

1
2
3
4
5
6
7
from datetime import datetime

now = datetime.now()
formatted = now.strftime("%A, %B %d %Y at %I:%M %p")
print(formatted)
# Friday, January 02 2026 at 07:00 PM

We can also use it on input date and time values, and have them presented to use in the format we want using these functions.

1
2
3
4
5
6
7
from datetime import *

yesterday = datetime(2026, 1, 2, 19, 0, 0)
formatted_datetime = yesterday.strftime("%A, %B %d %Y at %I:%M %p")
print(formatted_datetime)

# Friday, January 02 2026 at 07:00 PM

💡Tip: Think about the strftime function as a method to bring back more readable results from the numeric date and time.

Parsing/Translating DateTime

💡Tip: Parsing is a term I’ve frequently come across when learning to code. To be succinct, parsing in tech, is a term used to describe the process of either analysing or translating data into information that can then be used.

Parsing a datetime to an actual datetime object is useful, especially when we use input fields to take information from a user, which will sometimes be in a string format.

To parse a string input of date time into a date time object, we use .strptime(variable/input, "strftime format"). We must make sure that the format matches the input string; this enables the function to know which part of the string should be recognised as what for the parsing function to work.

1
2
3
4
5
6
7
8
9
from datetime import *

string_date = "2 January 2026" # Let's say that this is our user input

parsed_date = datetime.strptime(string_date, "%d %B %Y") # Parsing the string into an actual datetime object

print(parsed_date) # 2026-01-02 00:00:00

# Notice how this is still providing the time format, but with 0's, and that's because the function has translated the string as being a datetime object and then printed the complete result. We can also tell Python to only return/print off the date and not the time.

Splitting the Date and Time

So far, we’ve been able to learn how to use the datetime module to bring the complete date for us. What if we want the date or the time? Well, we can use the separate attributes to achieve that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from datetime import date, time

# Date Attribute:
date_input = date(2026, 1, 2)
print(date_input) # 2026-01-02

date_input = date(year=2026, month=1, day=2)
print(date_input) # 2026-01-02

date_input = date.today()
print(date_input) # 2026-01-02


# Time Attribute:
time = time(10, 30, 50)
print(time) # 10:30:50

#Using default parameters:
time = time(hour=10, minute=30, second=50)
print(time) # 10:30:50

#Using microsecond:
time = time(10, 30, 50, 200555)
print(time) # 10:30:50.200555

The examples should give a clear indication as to how you can use those attributes effectively. Keep in mind that we can also use both .strptime() and .strftime() here.

Calculating the Difference Between Dates

We can also calculate the difference between two points in time and bring that back as a result. It’s a nice feature to be able to use and do.

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
32
33
34
from datetime import *

# Method 1:
todays_date = date.today()
new_year_date = date(year=2027, month=1, day=1)
new_years = new_year_date - todays_date # We are using simple maths to calculate this

print("Time left until new year: ", new_years) # Time left until new year: 364 days, 0:00:00

# Method 2:
t1 = date.today()
t2 = datetime(year=2027, month=1, day=1, hour=0, minute=0, second=0)
difference = t2 - t1
print("Time left until new year: ", difference) # Time left until new year: 364 days, 0:00:00

########

# Using TimeDelta:
# - Doesn't calculate the difference but calculates the number of days in the parameters you provide:
# Built with ChatGPT
from datetime import timedelta

# Duration from Jan 2, 2026 19:00 to Jan 1, 2027 00:00
duration_until_new_year = timedelta(
    weeks=51,      # 51 weeks = 357 days
    days=6,        # remaining days = 364 - 357 = 7 → subtract 1 day for hours adjustment
    hours=5,       # remaining hours
    minutes=0,
    seconds=0
)

print("Duration until New Year 2027", duration_until_new_year) # Duration until New Year, 2026 19:00: 363 days, 5:00:00

# timedelta will always provide an output in days to give you the length of days up to a point your specify.

I probably should give the timedelta its own section to write on, though there isn’t much; however, all timedelta really does is generate a figure for the number of days within a specified parameter. You can still use days, weeks, hours, months etc to provide what time delta should use to calculate the days figure.

If you were to provide an input like timedelta(weeks = 1), it would return a result to say 7 days, 00:00:00.

Overview

This pass on this topic has been able to get me knowing the differences between using the DateTime attribute and the timedelta function, which wasn’t very clear on my first go. I’ve also been able to know what strptime and strftime do and how to use them effectively and efficiently. What I must pay attention to is the methods we can use to take a datetime as an input or use it as a timestamp.

If we were to design and create a task manager, we would need to be able to tell the system when we want to complete a certain task by and also use the current date and time to calculate how many days we have until that task needs to be completed. These are all inputs and need to be formatted. This is where our code begins to gain the right level of complexity needed to build code.

Footnote:

This post is licensed under CC BY 4.0 by the author.