Dates & Times in Python – datetime Module (10 Examples)

 

In this article, you’ll learn what date and datetime objects are and how to use them in Python programming.

The date and datetime modules provide the opportunity to work with dates and times. The difference between date and datetime objects is simply the fact that datetime objects include a time component in addition to a date component.

Since the datetime module contains all features of the date module, the examples will mostly be based on datetime objects.

Table of contents:

You’re here for the Python programming syntax, so let’s get straight to the examples!

 

Importing Modules

Firstly, we need to import the datetime module.

from datetime import datetime, date, timedelta         # loading the datetime module

 

Example 1: Initialize Date & Time Objects Using the date() & datetime() Constructors

To create date and datetime objects, we must utilize the corresponding constructors: date() and datetime(). Both constructors require the year, month, and day parameters; however, the extra parameters such as hour, minute, and seconds are optional.

date_1999_12_31 = date(1999, 12, 31)                   # constructing date object
print(date_1999_12_31)                                 # printing date object
# 1999-12-31
 
dt_2001_5_10 = datetime(2001, 5, 10, 12, 30, 0)        # constructing datetime object 1
print(dt_2001_5_10)                                    # printing datetime object
# 2001-05-10 12:30:00
 
dt_2001_5_27 = datetime(2001, 5, 27, 8, 55, 17)        # constructing datetime object 2
print(dt_2001_5_27)                                    # printing datetime object
# 2001-05-27 12:30:00

The previous Python code has initialized three different data objects:

  • date_1999_12_31 is a date object that contains only a date component, but no time component.
  • dt_2001_5_10 is a datetime object that contains both a date and a time component.
  • dt_2001_5_27 is another datetime object.

Note that we have used the date() constructor to create the date object, and the datetime constructor to create our two datetime objects.

 

Example 2: Parsing datetime Objects

Both object types can also be created from a string by employing certain parsing functions. In Example 2, I’ll explain how to convert a string to a datetime object using the datetime.strptime() function. I’ll show two examples for two different datetime strings below.

str_date_1 = "15-8-2035 21:5:40"                       # initializing example date as string
dt_from_str_1 = datetime.strptime(str_date_1, "%d-%m-%Y %H:%M:%S") # converting string to datetime object
print(dt_from_str_1)                                   # printing converted datetime object
# 2035-08-15 21:05:40
str_date_2 = "10:12:21 August/15/2035"                 # initializing example date as string
dt_from_str_2 = datetime.strptime(str_date_2, '%H:%M:%S %B/%d/%Y') # converting string to datetime object
print(dt_from_str_2)                                   # printing converted datetime object
# 2035-08-15 10:12:21

The examples show that the date string doesn’t have to be in a specific format, the only necessary thing is to add the proper string formatting into the function as a parameter.

The datetime.strptime() function has many features. In the present example, some of the most common ones were shown. You can check the corresponding documentation for the entire formatting list.

 

Example 3: Extracting Date or Time Components from datetime Objects

If you need to get the date and time components of a datetime object separately, you should use the datetime.time() and datetime.date() functions.

print(dt_from_str_2.time())                            # printing extracted time component
# 10:12:21
 
print(dt_from_str_2.date())                            # printing extracted date component
# 2035-08-15

You may also check out our tutorial on how to convert a datetime object to a date only string. It explains how to extract dates from datetimes in some more detail.

 

Example 4: Getting Today’s Date

If you need to get the date of the current day, you can use the date.today() or datetime.today() functions.

print(date.today())                                    # printing date.today()
# 2022-12-29

As you can see, I have written this tutorial at the 29th of December 2022. New year’s vacation starts soon! 🙂

 

Example 5: Getting Current Time

If the current time is also of interest in addition to the current date, then you can utilize the functions datetime.today() and datetime.now().

print(datetime.today())                                # printing datetime.today()
# 2022-12-29 19:48:37.421880
print(datetime.now())
# 2022-12-29 19:48:37.421888

The functions return almost the same output, the slight difference is due to the point in time when they were executed in Python. However, the structures of the two functions are not identical; the now() function has optional parameters enabling timezone modification as well.

It is important to note that there is no such thing as a date.now() because the date objects don’t have any daytime features.

 

Example 6: Subtracting datetime Objects

Example 6 illustrates how to subtract two datetime objects. In this example, I’ll use the two datetime objects initialized in Example 1.

td_1 =  dt_2001_5_27 - dt_2001_5_10                    # subtracting two datetime objects
print(td_1)                                            # printing the produced timedelta object
# 16 days, 20:25:17

As shown above, there’s a time difference of 16 days, 20 hours, 25 minutes, and 17 seconds.

 

Example 7: Adding timedelta Object to datetime Object

We can also add a timedelta object to a datetime object to get another datetime object. This can be considered as the reverse operation of the one shown in Example 6.

dt_add = td_1 + dt_2001_5_10                           # adding timedelta object to datetime object
print(dt_add==dt_2001_5_27)                            # printing the equality check result
# True

If you would like to learn more on how to add days, months, and years to a datetime object, please have a look here; and if you are keen to get more info on how to add seconds, minutes, and hours, please take a look at this tutorial.

 

Example 8: Subtracting timedelta Object from datetime Object

Like in the case of the addition operation, the subtraction of a datetime object from a timedelta object produces a datetime object as well. The previous set of objects can be used for the illustration.

dt_sub = dt_2001_5_27 - td_1                           # subtracting a timedelta object from a datetime object
print(dt_sub==dt_2001_5_10)                            # printing the equality check result
# True

We do also provide more detailed tutorials on how to subtract days, months, and years as well as seconds, minutes, and hours.

 

Example 9: Format datetime Objects Using strftime() Function

If you need another format to express a datetime object instead of the default format, you can use the strftime() function, which works in a reverse fashion of strptime().

The function divides the datetime object into the values of time units, and a string output is returned depending on the format specified in the input. The code formats are the same as for the strptime() function. Here is the documentation link, in case you need some further information.

Let’s apply the strftime() function to one of our datetime objects:

print(datetime.strftime(dt_2001_5_27, "%B %d %Y %H:%M:%S, Day of the Year: %j"))     # printing formatted datetime object
# May 27 2001 08:55:17, Day of the Year: 147

The strftime() function also works with date objects, but as they don’t have any time fields, the default value for the missing time units, which is 0, is printed out.

Have a look at the time component below, it shows zeros only:

print(datetime.strftime(date_1999_12_31, "%B %d %Y %H:%M:%S, Day of the Year: %j"))  # printing formatted date object
# December 31 1999 00:00:00, Day of the Year: 365

By the way, the strftime function can also be used to manipulate datetime columns in a pandas DataFrame. For more info, you may browse through this tutorial.

 

Example 10: Formatting by datetime.isoformat() Function

An alternative way for the formatting of datetime objects is provided by the datetime.isoformat() function. It has two parameters:

  1. a single-character separator used to specify the character between the date and the time parts of the output
  2. a threshold parameter used to cut off the time units smaller than the specified value (e.g. if hours are given as the input then the output doesn’t include minutes, seconds, or microseconds)

Have a look at the following three slightly different applications of the isoformat() function:

print(dt_2001_5_27.isoformat(sep = ' ', timespec="hours"))        # printing formatted datetime object
# 2001-05-27 08
print(dt_2001_5_27.isoformat(sep = '_', timespec="minutes"))      # printing formatted datetime object
# 2001-05-27_08:55
print(dt_2001_5_27.isoformat(sep = '#', timespec="microseconds")) # printing formatted datetime object
# 2001-05-27#08:55:17.000000

As you can see, we have selected different separators and cut off metrics.

 

Video, Further Resources & Summary

Would you like to learn more about using datetime objects? Then I can recommend having a look at the following video on my YouTube channel. In the video, I explain the Python syntax of this post.

 

The YouTube video will be added soon.

 

Besides the video, you may want to have a look at the other tutorials on this website. A selection of interesting tutorials can be found below:

 

In this Python programming tutorial, you have learned how to utilize date/datetime objects. In case you have any additional questions, don’t hesitate to let me know in the comments.

 

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Top