While working with scripts that require real-time data, we work with the dateutil module in order to schedule or retrieve data at a particular time, or just input data with the timestamp of retrieval.
Working with a lot of scripts and trying to manipulate date and time formats using the default
datetime module could be a daunting task, considering the number of changes to the data retrieved you need to make.
dateutil module was created in order to provide the functionality to make your life easier.
dateutil module specializes in providing an extension of features to the existing
datetime module, and as such, the installation of the
datetime module is a prerequisite.
However, since it’s a part of the Python standard library, there’s nothing to worry about.
Installing the dateutil module in Python
Before we get started working with the
dateutil module, we’ll need to install it on our computer first. So, let’s get to the installation procedure:
# The command to install the module, through the pip manager. pip install python-dateutil
Working with the dateutil module
If you’ve successfully installed the module, we can now proceed to work with it!
1.0. The module and it’s subclasses.
dateutil module is one split into a few different subclasses, and we’ll get into them right away so that you know what you’re working with,
- and a few more!
There aren’t too many subclasses to the module, but, we’ll only be delving into the functions of a few of them in this article.
1.1 Importing the required methods
We’ve already installed the module, and now just need to put the methods into action and get our results.
So, let’s get started with some of them!
Wait, we might have a few steps before working with the
dateutil module, and one of them is the need to import them first.
# We'll need to import methods from the datetime module as a base. import datetime # Now, let's import some methods from the dateutil subclasses. from dateutil.relativedelta import * from dateutil.easter import * from dateutil.parser import * from dateutil.rrule import *
These imports allow us to work with a lot of the methods that we’ll be needing through this article.
1.2 The datetime functionality
Before we get started working with the
dateutil module, you might recall the fact that the module kind of depends on the datetime module as well, right?
Well, that’s absolutely right. The
dateutil module works with datetime objects, and this means that we’ll need to create the datetime objects before working with them.
Hence, the reason for the
datetime module import. Let’s get to working with a few modules in
1.3. Datetime and relativedelta
relativedelta subclass extends off the
datetime module, providing us with features that allow us to work with dates and times, relative to the retrieved information.
This means that we can add days, months, or even years to the currently utilized
datetime object. It also allows us to work with intervals in time, with the
# Creating a few datetime objects to work with NOW = datetime.now() print("The datetime right now : ", NOW) TODAY = date.today() print("The date today : ", TODAY)
Now, let’s work with retrieving information using relative dates.
# Next month print(NOW + relativedelta(months=+1)) # Next month, plus one week print(NOW + relativedelta(months=+1, weeks=+1)) # Next month, plus one week, at 5 PM print(NOW + relativedelta(months=+1, weeks=+1, hour=17)) # Next friday print(TODAY + relativedelta(weekday=FR))
A more applicable use of this module would be to find out information using a few small operations.
# Finding out the last tuesday in the month print(TODAY + relativedelta(day=31, weekday=TU(-1))) # We can also work with datetime objects directly # Example: Age of Sacra sacra_birthday = datetime(1939, 4, 5, 12, 0) print("Sacra's Age : ", relativedelta(NOW, sacra_birthday).years)
If you’ve noticed, we’ve retrieved only the
years from the
This was used for a clean output, but, in case you wish to find out exactly how much older Sacra really is, try fiddling with the relativedelta object for yourself. 😉
1.4. Datetime and easter
easter subclass is used to calculate date and time with generic easter calendars, allowing for calculation of datetime objects with respect to a variety of calendars.
The subclass is pretty small and there’s only one argument with three options that defines the entire module.
- The Julian Calendar, EASTER_JULIAN=1.
- The Gregorian Calendar, EASTER_ORTHODOX=2
- The Western Calendar, EASTER_WESTERN=3
Using them in code, would look much like,
# The Julian Calendar print("Julian Calendar : ", easter(1324, 1)) # The Gregorian Calendar print("Gregorian Calendar : ", easter(1324, 2)) # The Western Calendar print("Western Calendar : ", easter(1324, 3))
1.5. Datetime and parser
parser subclass brings into picture a superior date/time string parser, which is known to be able to parse multiple known formats representing a date or a time.
# The parser subclass print(parse("Thu Sep 25 10:36:28 BRST 2003")) # We can also ignore the timezone which is set to default locally print(parse("Thu Sep 25 10:36:28 BRST 2003", ignoretz=True)) # We can also not provide a timezone, or a year # This allows for it to return the current year, with no timezone inclusion. print(parse("Thu Sep 25 10:36:28")) # We can also provide variables which contain information, as values. DEFAULT = datetime(2020, 12, 25) print(parse("10:36", default=DEFAULT))
There are a lot of options you can provide, which include timezones, locally or explicitly.
Stripping down information to provide the timezones, year, time, can be done using variables passed into the function as default arguments, which you can look into here.
1.6. Datetime and rrule
rrule subclass uses input to provide us with information on the recurrence of a
datetime object, and the
datetime objects respectively.
# The rrule subclass # Daily repetition for 20 occurrences print(list(rrule(DAILY, count=20, dtstart=parse("20201202T090000")))) # Repeating based on the interval print(list(rrule(DAILY, interval=10, count=5, dtstart=parse("20201202T090000")))) # Weekly repetition print(list(rrule(WEEKLY, count=10, dtstart=parse("20201202T090000")))) # Monthly repetition print(list(rrule(MONTHLY, count=10, dtstart=parse("20201202T090000")))) # Yearly repetition print(list(rrule(YEARLY, count=10, dtstart=parse("20201202T090000"))))
A great feature of the
dateutil module, this subclass could allow you to work with a lot of scheduling tasks, and calendar storage innovations.
There’s a lot more to the modules themselves, and in case you wish to learn more about the features and the arguments on a deeper level, it’s a good idea to check out the Documentation.
If you’ve gone through this article, you now know how the
dateutil module allows us to extend the information provided by the
datetime module to produce results that you’d normally need to calculate or process.
Life’s a lot simpler if you know which module to look towards in order to work on something.