Python's Built In Modules: The Datetime Module

Python's Built In Modules: The Datetime Module

It has been quite some time since my last blog post but we haven’t gone off track in our built-in modules python series. The module we would be looking at today is something we may all relate to as sleep deprived developers - coffee; I mean datetime. It is a module that deals with handling date and time in python programs. We would have a look at the different ways we could use it in our code.

Let’s have a look at a basic task with the datetime module. Imagine you would like to get the date and time at this moment because you are entitled a coffee break. You could simply use the snippet below;

import datetime 

coffeeTime = datetime.datetime.now()
print(coffeeTime)

Using the above, you would be able to get the local date and time in the format below:

2024-10-30 16:46:20.423556

Datetime Classes

There are several classes of the datetime module and they are used based on what you would like to do with them. We would briefly examine a number of them below.

datetime

As we have seen above, this represents both the local date and time.

from datetime import datetime

coffeeTime = datetime.now()
print(coffeeTime)

date

This represents just the local date without including the time.

from datetime import date
coffeeDay = date.today()
print(f"In month {coffeeDay.month}, day {coffeeDay.day}, {coffeeDay.year} there was a coffee tsunami!")

The above snippet shows the current date.

time

You can probably already guess that this represents the local time only. You can refer to a specific time.

from datetime import time

coffeeTime = time(13, 50, 30)
print(f"{coffeeTime.hour}:{coffeeTime.minute}:{coffeeTime.second} is the time for my coffee break!")

timedelta

Here we are concerned with differences between dates and times. Usually used for datetime calculations.

from datetime import timedelta, datetime

delta = timedelta(days=3)
presentCoffee = datetime.now()
futureCoffee = presentCoffee + delta
print(futureCoffee)

The snippet returns a date and time that’s exactly three days from the present moment.

strftime and strptime

Datetime objects are not strings. To convert them into strings in different formats, we use strftime.

from datetime import datetime

coffeeTime = datetime.now()
coffeeTimeString = coffeeTime.strftime("%d/%m/%Y %H:%M:%S")
print(coffeeTimeString)
print(type(coffeeTimeString))

Note that %d, %m, %Y, %H, %M and %S represent day, month, year, hour, minute and second respectively. When you inquire the type of coffeeTimeString, you get str which checks out since it is a string.

If you’d like to revert from strings to the datetime object, you use strptime. When you print out the type of coffeeTime, you get datetime.datetime which is the datetime object.

from datetime import datetime

coffeeTimeString = "30/10/2024 21:57:30"
coffeeTime = datetime.strptime(coffeeTimeString, "%d/%m/%Y %H:%M:%S")
print(coffeeTime)
print(type(coffeeTime))

timezone

If you’re ever working on a project where working with timezones is important because you are taking different regions into consideration, you’ll find the timezone class of the datetime module important. You can define a timezone with the UTC (Universal Time Constant) standard and make your calculations based on offsets from this timezone. Bostwana for instance is in the UTC + 2 timezone. If I were working with that time in a project, I could try:

from datetime import datetime, timezone, timedelta

BostwanaOffset = timezone(timedelta(hours=2))
currentTimeInBostwana = datetime.now(BostwanaOffset)
print(currentTimeInBostwana)

The above constitutes just a subset of the awesome things you could do with the datetime module. Check out the python docs for more on it. We’ve talked briefly about handling time programmatically, but I should add that you should always find some time to rest or we’d have a coffee tsunami on our hands.