Python datetime Tutorial with Examples

Python Datetime() Module

This is a detailed tutorial of the Python datetime module. Learn to do various things related to date and time in python with the help of examples.

Python datetime Module

In case you want to work with date and time in python, you can make use of the datetime module. You can simply import this module in any of your Python programs and can do various things that are associated with date and time. Here in this article, I’ve illustrated the usage of this module for different sorts of things with the help of illustrative examples.

Getting Current Date & Time

The very basic usage of this module is to get the current time in python. To get the current date and time, you need to make use of the method of this module.

Example. The following code snippet is fetching the current date and time using this module and printing it on the console screen.

Python Datetime Get Current Time Example

The code is simple. We’ve simply imported the DateTime module using the import statement and then have used the method to get the current date and time. The method returns a datetime object and this you can clearly see in the output screenshot of the above python code snippet in which we’ve used the type function to check to which class the object variable obj belongs to.

The date and time information so returned is according to the local time of your computer.

Getting Current Date

In the above example, you can clearly see that the full date and time are being returned by the method. But in case, if you only want to get the current date you can make use of another method,

Example. In this code snippet, we’re fetching the today’s date and also verifying that the class of the returned object is

Python Get Current Date Only Example

You can clearly see in the above screenshot that the today date is being printed and it belongs to the class.

Different Classes of the datetime Module

Upto here, you might have seen datetime module is a little different from most of the other python modules that have direct methods. But here, you can observe that the datetime module further has many classes such as the datetime and the date class and further these classes have their own methods such as and

We can make use of the dir() function to check all of the classes under the datetime module. We’ve done so in the following code illustration.

Python Datetime Classes

You can clearly see the names of different classes under the datetime module in the above screenshot including the datetime and date classes. time and timedetla are the other two classes that are used commonly. Let’s talk about each of these classes in detail one by one. Class

I’ve already illustrated an example above that makes use fo the class to fetch the current date. This class is used to represent a date with three components, i.e. date, month and year. In the above example, we’ve used the method today() to fetch the current date using this class, but you can always create your own object by defining the three components, year, month and date in order. It is mandatory to provide all of these three arguments to create a valid date object.

Example. Here we’re creating a object by defining the three components of the date.

Here we’ve provided the three components of the date as the three arguments to the method and hence it creates a new date object that contains the desired date as shown in the following output screenshot as well.

Python Object Example

In case, you just want to work with date and not the time part, you can import only the date class from the datetime module and can use its methods directly. In the following example, we’re using this approach to fetch the today date using the today method i.e. directly applied on the date class object.

Python Datetime Module Date Class Example

Creating date from timestamp

The date class has a method fromtimestamp() using which you can convert a timestamp into a date object. This method takes the timestamp value as the argument and returns the corresponding date as the date object.

Example. Here we’re converting a specific timestamp into the corresponding date.

Here you can clearly see that the timestamp value 1584255321 is being converted into its corresponding date i.e. 15 March 2020.

Python Date From Timestamp Example

Getting Day, Month and Year Individually

In case you just want a particular component of the date-object such as only day, only month or only year, you can do it simply by applying the day, month and year properties.

Example. In the following python code, we’re fetching the date, month and year of today’s date individually and printing them to the console.

As you can see in the above code, you just need to apply the day, month or year properties to fetch the particular component from a date-object.

Python Get Day, Month And Year Individually Example

datetime.time Class

As the object is composed of the three components, day, month and year, the datetime.time object may be composed of upto four components. These four components are hour, minute, second and microsecond respectively. You may or may not provide all the arguments at one time and hence accordingly the time object will be created.

Example. Here, we’re creating five different time objects by providing the different numbers of arguments each time.

Python Datetime Module Time Object Example

All of these four arguments have the default value 0. Therefore, in case, you do not provide the value for anyone of the argument, it will be assumed 0 by default and this has been already shown in the above screenshot.

Getting hour, minute, second and microsecond Individually

Similar to fetching the individual components of date using day, month and year properties, you can also fetch the different components from the time object, using the hour, minute, second and microsecond properties.

Example. The following example illustrates this concept.

Python Datetime Module Time Object Getting Hour, Minute, Second Or Microsecond Individually Example

datetime.datetime Class

The datetime.datetime class contains features for both the date and time classes. The datetime.datetime() method can take upto seven different components of the date and time. These components in order are year, month, date, hour, minute, second and microsecond. Once, you create a valid datetime object by providing the values for these components, you can apply a lot of different useful methods on this object to fetch more useful information associated with date and time.

To create a valid datetime object, you must specify at least the first three components namely, year, month and date. The other four components, that are the components of time have the default value set to be 0. So even if you will not provide those components, the value will be automatically assumed to be 0 for them.

Python Datetime Module Datetime Object Example

Fetching date and time components individually from datetime object

You can also fetch the individual components from the datetime object similar to the date and time objects using the components-specific properties as illustrated in the following example.


Python Datetime Object Example Fetching Individual Date And Time Components

Creating timestamp from datetime object

You can easily fetch the timestamp from a valid datetime object using the timestamp() method.

Example. Here we’ve first created a valid datetime object by providing the different components of date and time and then fetching the timestamp using the timestamp() method.

Python Get TimeStamp From Datetime Object Example

datetime.timedelta Class

The term delta is often used for difference and hence timedelta class of the Python datetime module is used for the date and time differences.

Example. In the following code, we’re first checking the difference between two date objects and then the difference between the two datetime objects.

Here, we’ve also used the type method to check to which class the different belongs to and you can clearly see in the output screenshot that it belongs to the timedelta object.

Python Date And Time Different Timedelta Example

timedelta can also be Negative

In case you’re subtracting the date or time from the date or time that is already ahead of the other date and time, you may get a negative timedelta as well.

Example. This is the same example as given above. The difference is just that we’ve interchanged the positions of the date and time objects, while they’re getting subtracted to give negative timedelta objects.

You can clearly see the Negative timedelta objects returned in the following output screenshot.

Python Negative Timedelta Objects Example

Note. You can also apply the abs() function to the negative timedelta object to make it positive.

Difference between timedelta Objects

The difference between the two timedelta objects can also be calculated in the same way using the subtraction operator. We’ve used the two timedelta objects from the above example and then subtracted them from each other.

Python Timedelta Objects Difference Example

Creating a timedelta Object

You can also define your own timedelta Object by defining the five components as arguments to the timedelta() method. All of these five arguments are optional and have default values set to 0. The five components here are namely, days, hours, minutes, seconds and microseconds.

Example. Here we’ve created a time delta object by providing all of the components-specific arguments.

Python Timedelta Object Creation Example

Evaluating Seconds from timedelta Objects

The timedelta object contains duration of time in terms of the number of days, hours, minutes, seconds and microseconds. But you can also get the total timedelta object duration in seconds only using the total_seconds() method.

Here you can see, we’ve got the timedelta object duration in seconds.

Pytho Timedelta Object Into Total Seconds Example

Note. The + operator can also be used to add two dates and times.

Multiplying timedelta Objects

The time delta Objects can also be multiplied with float and integer numbers but not with other timedelta Objects.

Example. Here we’ve multiplied timedelta objects with integers and floating-point numbers.

Python Timedelta Object Multiplication With Integers And Floating Point Numbers Example

Formatting date & time in Python

The format of the date is really important. In different countries across the world, people make us of different date formats. For example, in the United States, mm/dd/yyyy is more popular while in countries like India and the UK, the dd/mm/yyyy format is often used. Well, that’s not an issue here as you can print out the date and time in the format you like to do.

The Python datetime module offers a strftime() method that can be used to print the date and time in your desired format.

Example. Here we’re first fetching the current time to create a datetime object and then we’re applying strftime() method on this object to print the date and time in different desired formats.

Python Datetime Module Strtime() Example

The different symbols that you can use for the formatting of the date and time can be found here on the website This method converts the datetime object into a plain string that contains date or time in the desired format.

String To datetime using strptime() method

The method strptime() is a kind of reverse function of the strftime() method. You can use this method to convert a string containing date and time information into a valid datetime object. This is one of most of the methods of the datetime module that is popularly used by the developers.

Example. In the following code, we’re converting the plain string date and time information into a datetime object.

The strptime() method takes two arguments. The first argument is the date and time information as a string. The second argument is the format in which you’ve provided the date and time information in the first argument. Here %d represents the day i.e. 30, %B represents the full month name, i.e. March and %Y represents the year i.e. 2020.

Python Datetime Strptime() Method Example

Timezone & datetime Module

There’s another module named pytz that can be used to handle your date and time information for different time zones. By default, when you’re using the datetime module, you’re referring to the timezone of your local machine. But you may also be wanted to keep your date and time information according to other timezones of the world. Let’s see how you can do so using the Python pytz module.

Example. The following code illustrates how you can fetch the time and date information of the different timezones using the pytz module.

Python Datetime Pytz Module Example For Different Timezones

This way, you can do a lot of productive stuff using the Python datetime module.

I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.

And do not forget to subscribe to WTMatter!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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