Datetime Arithmetic, Alteration and Truncation with Python's Delorean

Introduction

Working with datetime can be a bit daunting and challenging, and handling datetime in Python is no exception. Python's built-in datetime module introduced us to several classes - date, datetime, time, timezone and timedelta, and several external libraries have spawned to address the issues present in the official module, such as Arrow.

In this guide, we'll take a look at how to perform time and date arithmetic, alteration and truncation of datetime objects in Delorean - a library built upon pytz which is the standard library for solving problems relating to time zones, and dateutil which is used to calculate deltas between any 2 given datetime objects.

Installing Delorean Setting Up a Virtual Environment

Delorean is available for installation via pip. It is generally advisable to work in a virtual environment because it enables you to organize dependencies required by different projects isolated.

On Linux, or MacOS to create a virtual environment, we'd run:

$ python3 -m venv env
$ source env/bin/activate
$ python3 -m pip install delorean

Alternatively, on Windows we can run:

$ virtualenv env
$ .\env\Scripts\activate
$ python3 -m pip install delorean

Adding and Subtracting Time with Timedelta

timedelta represents the difference between two datetime objects, and has a microsecond resolution. Using timedelta, we can define durations of different length, such as microseconds, seconds, minutes, hours, days and weeks.

It doesn't contain any information about dates - just the duration. The timedelta between the 5th of June and the 10th of June is the same as the timedelta between the 5th of May and the 10th of May - 5 days.

This makes it really easy to add or subtract a duration of time from datetime objects:

from delorean import Delorean
import datetime

dt_tm_future = Delorean()
dt_tm_future += datetime.timedelta(days=3)

dt_tm_past = Delorean()
dt_tm_past -= datetime.timedelta(weeks=3)

print("The date 3 days from now is: ", dt_tm_future)
print("The date 3 weeks before now was: ", dt_tm_past)

This results in:

The date 3 days from now is:  Delorean(datetime=datetime.datetime(2021, 7, 17, 10, 22, 51, 403546), timezone='UTC')
The date 3 weeks before now was:  Delorean(datetime=datetime.datetime(2021, 6, 23, 10, 22, 51, 403643), timezone='UTC')

Get Number Of Days Between Dates with Delorean

A common unknown with multiple dates is the number of days between two given dates. This result is typically packed in a timedelta object given the fact that it's designed to represent this difference.

Given how easy it is to add or subtract timedelta from and to dates, it's only natural that this operation is easy as well.

To get the number of days between two dates in Python with Delorean, we just subtract the dates, which results in a timedelta representation of the difference:

present_date = Delorean()
new_year = Delorean(datetime=datetime.datetime(2022, 1, 1), timezone='UTC')
until_new_year = new_year - present_date
print("Days until 2022 ", until_new_year)
print("Days till 2022 ", until_new_year.days)

We can print the entire timedelta object, or just access its days attribute:

Days until 2022  170 days, 13:24:22.817417
Days till 2022  170

Alteration of Time and Date

Delorean lets you effortlessly alter datetime objects by replacing or shifting values. For this, we use the replace() and shift() methods.

The replace() method lets you replace a certain aspect of the datetime instance, while shift() lets you shift the timezone:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

from delorean import Delorean

date = Delorean(datetime=datetime.datetime(2021, 5, 14, 12), timezone='Europe/Paris')

altered_tm = date.replace(hour=10)
altered_dt = date.replace(month=10)

print("Altered time is:", altered_tm)
print("Altered date is:", altered_dt)

altered_dt.shift('US/Pacific')
print("Shifted object:", altered_dt)

We've created a Delorean instance, changed its hour and month attributes, and then shifted the new, altered datetime object into a new timezone:

Altered time is: Delorean(datetime=datetime.datetime(2021, 5, 14, 10, 0), timezone='Europe/Paris')
Altered date is: Delorean(datetime=datetime.datetime(2021, 10, 14, 12, 0), timezone='Europe/Paris')
Shifted object: Delorean(datetime=datetime.datetime(2021, 10, 14, 3, 0), timezone='US/Pacific')

Truncate Datetime Objects with Delorean

Depending on the reason you're using datetime for - you might not care about the smaller-order measurements such as seconds or milliseconds. While you can simply print out the data without the measurements - you can also truncate() them out of the Delorean object itself.

The method works on higher-order measurements as well, and accepts all valid Delorean time frames, up to years:

from delorean import Delorean

date = Delorean()
print("Date before truncation:", date)

trun_min = date.truncate('minute') # Truncate to minutes
print("Truncated to minutes = ", trun_min)

It's worth noting that you're truncating to a certain measurement level. That's to say - if you truncate to minutes - seconds and milliseconds will be dropped. In essence - you're setting the resolution of the Delorean instance:

Date before truncation: Delorean(datetime=datetime.datetime(2021, 7, 14, 10, 52, 9, 893770), timezone='UTC')
Truncated to minutes =  Delorean(datetime=datetime.datetime(2021, 7, 14, 10, 52), timezone='UTC')

Conclusion

In this guide, we've taken a look at how to perform time and date arithmetic, alteration and truncation in Python with Delorean.

Last Updated: March 7th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Geoffery, JosephAuthor

I am a software developer with interests in open source, android development (with kotlin), backend web development (with python), and data science (with python as well).

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms