How To Work With Python Dates

How To Work With Python Dates

Working with Python dates, or any programming language for that matter, is always challenging. You can get confused due to the number of existing standards, which aren’t always supported by every language. We can help you become adept in date representations and operations in Python with this guide.

Python Dates

There are built-in and third-party modules in Python that allow you to manipulate dates, many of which also support time manipulation:

  • datetime: the module you are mostly likely to rely on when working with dates and times in Python.
  • calendar: this module provides many calendar-related operations.
  • zoneinfo: comes with support for time zones.
  • dateutil: this third-party library offers many powerful additional functions to the built-in datetime module.

In this tutorial, we will explore the datetime module since it provides the most basic and most commonly used date and time functions in Python.

The datetime module

This module provides many classes for different date and time types: datetime.date, datetime.time, datetime.datetime, datetime.timedelta, and datetime.timezone.

Instances of these classes are immutable, meaning you can’t modify them after their creation. You can use the date class and its method to work with components of a day like years, months, and days, the datetime class if you want to work with times and dates together, and the timedelta class when there is a need for date intervals.

datetime.date Constructors

You can create a date object by calling the date() constructor and providing the year, month, and day values:

datetime.date(year, month, day)

Example:

>>> from datetime import date
>>> newyear = date(2022, 1, 1)
>>> type(newyear)
<class 'datetime.date'>

The datetime module also supports week-based dates with date.fromisocalendar(). You only need to provide the year, the week, and the day of the week. This is how you can get the date of the second day of the fifth week in 2022 (it is February 2):

>>> date.fromisocalendar(2022, 5, 2)
datetime.date(2022, 2, 1)

There are also other special constructors in the date class. By invoking date.today(), you will get a date object representing the current date in your local time.

>>> current_date = date.today()
>>> current_date
datetime.date(2022, 10, 20)

You can also get a date by providing its ordinal value with date.fromordinal(). January 1 of year 1 has ordinal 1, and so on.

>>> date_10_000 = date.fromordinal(10000)
>>> date_10_000
datetime.date(28, 5, 18)

datetime.date Attributes, Operations, And Methods

You can use the name of a date object or the print() function to print a string representation of its value:

>>> newyear
datetime.date(2022, 1, 1)
>>> print(newyear)
2022-01-01

However, the isoformat() method is the formal way to produce a string representation of a date object in ISO 8601 format. This format represents dates and times by going from the most general component (year) to the most specific (day).

>>> newyear.isoformat()
'2022-01-01'

The ctime() method is another option for displaying the date as a string. It uses the native C function ctime() in your system to produce a string representation conforming to the C standard:

>>> newyear.ctime()
'Sat Jan  1 00:00:00 2022'

For more formatting options, use the strftime() method. It provides plenty of directives with which you can customize the string output. For example:

>>> newyear.strftime('%B %d, %Y')
'January 01, 2022'

Remember that these values should be within their valid ranges. It is from 1 to 12 for the month, 1 and the number of days in that month for the day, and from 1 to 9999 for the year. If one of the components falls out of its valid range, Python will give you a ValueError exception.

>>> example = date(2022, 13, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: month must be in 1..12

You can get the earliest and latest dates supported by the date class with the min and max attributes:

>>> date.min
datetime.date(1, 1, 1)
>>> date.max
datetime.date(9999, 12, 31)

If you have a string representation of the date in ISO 8601 format, the date.fromisoformat() method can convert it to a date object as well:

>>> date.fromisoformat('2022-09-30')
datetime.date(2022, 9, 30)

Once you have a date object, you can get the day, month, and year components with instance attributes of the same name:

>>> current_date.day                                                                             
20
>>> current_date.month
10
>>> current_date.year
2022

To get the date of the week, use the weekday() method:

>>> current_date.weekday()
3

The returned value is an integer from 0 to 6, where 0 is Monday, and 6 is Sunday. In this case, number 3 indicates today is Thursday. If you want the counting to start from 1 instead, use the isoweekday() method as an alternative:

>>> current_date.isoweekday()
4

You can compare different date objects:

>>> date1 = date(2022, 9, 10)
>>> date2 = date(2022, 10, 4)
>>> date1 < date2
True
>>> date1 > date2
False
>>> date1 == date2
False

To add or remove days from a date object, you will need to use timedelta objects (which are also provided by the datetime module). These objects support the resolution down to seconds, but here you only need to use the days or weeks arguments to set the difference between dates.

>>> from datetime import timedelta
>>> delta1 = timedelta(days = 50)
>>> delta2 = timedelta(weeks = 2)
>>> current_date + delta1
datetime.date(2022, 12, 9)
>>> current_date + delta2
datetime.date(2022, 11, 3)

You can use the subtraction operation to count days to a day in the future. This calculation tells us that there are 108 days between today (October 20) and February 5 in the next year:

>>> event = date(2023, 2, 5)
>>> (event - current_date).days
108

Remember that timedelta objects support many other operations in case you need to modify them. You can multiply or divide them by an integer or float:

>>> delta1*5
datetime.timedelta(days=250)
>>> delta1/10
datetime.timedelta(days=5)

And, of course, you can find the sum or difference of two timedelta objects as well. These operations return timedelta objects:

>>> delta1 + delta2
datetime.timedelta(days=64)
>>> delta1 - delta2
datetime.timedelta(days=36)

In these examples, we create two timedelta objects representing 50-day and 2-week durations. They can be used to add to existing date objects, creating a new date object representing the resulting date.

To replace certain components of a date, you can use the replace() method. Since date objects are immutable, it doesn’t modify an existing object. However, it can return a new date that has the same components, except for those you have set new values. For example, this is how you can replace the current day with 30:

>>> current_date
datetime.date(2022, 10, 20)
>>> current_date.replace(day = 30)
datetime.date(2022, 10, 30)

Tutorials

You can learn more about Dates in Python in the articles below:

Summary

There are many modules that can help you work with Python dates. The datetime module is the most important one, providing several classes and methods for manipulating dates.

Leave a Reply

Your email address will not be published. Required fields are marked *