<img alt="python datetime" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/python-datetime.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

The Python DateTime class is an important feature of the Python language.

It can be used to create, store, and manipulate dates. This article is a guide on the useful methods of the Python DateTime object used to record dates and perform calculations involving dates.

What is the DateTime Class in Python?

The DateTime module in Python is a built-in object that represents both a date and time. With this object, you can easily parse dates meaningfully and make calculations using them.

It exposes various methods to do this. These methods will be discussed in the sections that follow.

Useful Methods on the DateTime Class

This section will discuss the common methods and properties used on the Python DateTime object. I will also demonstrate these methods with code examples.

To follow along, you must have Python3 installed and a code editor. If you do not have those, you can use our online IDE.

To use dates in Python, you must import the datetime module from the datetime package like so:

from datetime import datetime

The code examples below will assume that you already have that import.

now()

The first and probably most important method in the Python DateTime module is the now method. The now method is a static method that returns the current time in your time zone. For example:

now = datetime.now()

You can print out the object using the print function. This will print out a string representation of the object using the __str__ magic method.

print(now)

And this will be your output:

<img alt="Python-DateTime-Tutorial" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Python-DateTime-Tutorial.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

The type of this object is a DateTime. You can see this by running the following code:

print(type(now))
<img alt="DateTime-Object-Type" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/DateTime-Object-Type.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

strftime()

Any date or time in Python is represented using an object of the DateTime class. However, to display the date or store it in a database, you must convert it to a string. This can be done using the strftime method.

The method takes in one argument, a string representing the format to convert the date to.

For example, you could do the following:

# Creating date, right now
now = datetime.now()

formatted_date = now.strftime('%d/%m/%Y')

print(formatted_date)

In this case, the %d will be substituted with the correct date. The %m will be converted to the correct month, and the %Y will be converted to the correct year. The full list of formatting options can be found :

The result of the code above would be:

<img alt="Python-strftime" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Python-strftime.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

strptime()

While strftime formats a DateTime object into a string, strptime does the opposite. It parses a string into a DateTime object. This method is static, meaning it is available in the class itself. To use it, you pass in two arguments: the string that contains the date and the string that contains the format. For example:

date_string = '4/10/2023'
format_string = '%d/%m/%Y'

parsed_date = datetime.strptime(date_string, format_string)

print(parsed_date)
<img alt="Python-strptime" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Python-strptime.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

isoformat()

The isoformat method can be used to format dates into ISO Format 8601. This provides a standard way to format a date without specifying the format as you do with strftime.

now = datetime.now()

iso_formatted_date = now.isoformat()

print(iso_formatted_date)

The strftime and strptime methods can be used to format and parse dates. However, in each case, you must specify the format you are writing to and reading from. This can become cumbersome after some time. If only there were a way to format dates into a standard format from which you can parse them.

<img alt="Python-DateTime-Isoformat" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Python-DateTime-Isoformat.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

fromisoformat()

The inverse of isoformat is the fromisoformat method. This method will read a date string formatted according to ISO 8601 and parse it into a Python DateTime object. This method is available in the DateTime class and is called with the date_string you want to pass. It will return a Python DateTime object parsed for you.

date_string = '2023-10-04T22:31:52.346060'

parsed_date = datetime.fromisoformat(date_string)

print(parsed_date)
<img alt="python-datetime-fromisoformat" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/python-datetime-fromisoformat.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

timetuple()

The DateTime object stores a date and time in a collection of properties. Example properties would be month and year. You can use methods like the ones demonstrated below to access these properties.

now = datetime.now()

year = now.year()
month = now.month()

However, oftentimes, you would want to access all these properties at once. That is what the timetuple method is for. It returns the DateTime object as a tuple. The order of the values in the tuple is expressed in the table below:

Index Item
0 Year
1 Month of the Year (1 – 12)
2 Date of the Month (1 – 31)
3 Hour of the Day (0 – 23)
4 Minute of the Hour (0 – 59)
5 Second of the Minute (0 – 59)
6 Day of the Week (0 – 6) where 0 represents Monday, and 6 Sunday
7 Day of the Year (1 – 366) where 1 is Jan 1st
8 Daylight Savings Time

Here’s an example where we get the timetuple and print it out.

time_tuple = now.timetuple()

print(time_tuple)
<img alt="DateTime-Tuple" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/DateTime-Tuple.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

timedelta()

The timedelta class is technically different from the DateTime class. However, it is important so that we will cover it here. The best way to explain is to demonstrate, so here is an example.

from datetime import datetime, timedelta

# Creating a date now
now = datetime.now()

# Creating a time delta for one day
change = timedelta(days=1)

# Adding a time delta to today
tomorrow = now   change

print(tomorrow)

As you can see from the code snippet above, change it is a timedelta object that represents a change in one day. This timedelta object can be added to a DateTime object to get tomorrow’s date. However, you can also subtract it to get yesterday’s date before.

<img alt="Time-Delta" data- data-src="https://kirelos.com/wp-content/uploads/2023/10/echo/Time-Delta.png/w=576" data- decoding="async" height="446" src="data:image/svg xml,” width=”576″>

Conclusion

In this article, we covered the DateTime Class in Python and some of the most useful methods on the DateTime objects.

Next, check out our article on the best Python Cheat Sheets.