This is a detailed tutorial on 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 into 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 datetime.now()
method of this module.
Example. The following code snippet is fetching the current date and time using this module and prints it on the console screen.
import datetime obj = datetime.datetime.now() #Returns datetime object print(obj) print(type(obj))
The code is simple. We’ve simply imported the DateTime module using the import statement and then have used the datetime.now()
method to get the current date and time. The datetime.now()
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 datetime.now()
method. But in case, if you only want to get the current date you can make use of another method, date.today()
.
Example. In this code snippet, we’re fetching today’s date and also verifying that the class of the returned object is datetime.date
.
import datetime date = datetime.date.today() #Returns date object print(date) print(type(date))
You can clearly see in the above screenshot that today’s date is being printed and it belongs to the datetime.date
class.
Different Classes of the datetime
Module
Up to 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 datetime.now()
and date.today()
.
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.
import datetime print(dir(datetime))
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.
datetime.date
Class
I’ve already illustrated an example above that makes use of the datetime.date
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 datetime.date
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 datetime.date
object by defining the three components of the date.
import datetime #Defining a datetime.date object date = datetime.date(2020,3,25) print(date)
Here we’ve provided the three components of the date as the three arguments to the datetime.date()
method and hence it creates a new date object that contains the desired date as shown in the following output screenshot as well.
In case, you just want to work with the 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 to the date class object.
from datetime import date #Fetching today's date. print(date.today())
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.
from datetime import date #Fetching date from timestamp date_obj = date.fromtimestamp(1584255321) print(date_obj)
Here you can clearly see that the timestamp value 1584255321
is being converted into its corresponding date i.e. 15 March 2020
.
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.
from datetime import date #Getting Current Date date_obj = date.today() #Fetching Only Day print(date_obj.day) #Fetching Only Month print(date_obj.month) #Fetching Only Year print(date_obj.year)
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.
datetime.time
Class
As the datetime.date
object is composed of three components, day, month, and year, the datetime.time
object may be composed of up to 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 different numbers of arguments each time.
from datetime import time #No Arguments time_obj = time() print(time_obj) #Providing hour time_obj = time(15) print(time_obj) #Providing hour, minute time_obj = time(15,23) print(time_obj) #Providing hour, minute, second time_obj = time(15,23,54) print(time_obj) #Providing hour, minute, second, microsecond time_obj = time(15,23,54, 112256) print(time_obj)
All of these four arguments have the default value 0
. Therefore, in case, you do not provide the value for any one of the arguments, 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.
from datetime import time #Creating time object time_obj = time(1,2,3,523124) #Fetching only hour print(time_obj.hour) #Fetching only minute print(time_obj.minute) #Fetching only second print(time_obj.second) #Fetching only microsecond print(time_obj.microsecond)
datetime.datetime
Class
The datetime.datetime
class contains features for both the date and time classes. The datetime.datetime()
method can take up to 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, which 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.
from datetime import datetime #Date and Time Components year = 2020 month = 3 day = 13 hour = 19 minute = 24 second = 35 microsecond = 123123 #Creating only date datetime_obj = datetime(year, month, day) print(datetime_obj) #Creating full datetime object datetime_obj = datetime(year, month, day, hour, minute, second, microsecond) print(datetime_obj)
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.
Example.
from datetime import datetime #Creating full datetime object datetime_obj = datetime(2020, 3, 14, 10, 12, 34, 567221) #Fetching Only Day print(datetime_obj.day) #Fetching Only Month print(datetime_obj.month) #Fetching Only Year print(datetime_obj.year) #Fetching only hour print(datetime_obj.hour) #Fetching only minute print(datetime_obj.minute) #Fetching only second print(datetime_obj.second) #Fetching only microsecond print(datetime_obj.microsecond)
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.
from datetime import datetime #Creating full datetime object datetime_obj = datetime(2020, 3, 14, 10, 12, 34, 567221) #Fetching Timestamp print(datetime_obj.timestamp())
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.
from datetime import date, datetime #First Date date1 = date(2020, 2, 20) #Second Date date2 = date(2020, 3, 20) difference = date2 - date1 #Returns timedelta object print(difference) print(type(difference)) #First time datetime1 = datetime(2020, 2, 20, 10, 10, 10, 101010) #Second time datetime2 = datetime(2020, 3, 20, 15, 15, 10, 111111) difference = datetime2 - datetime1 #Returns timedelta object print(difference) print(type(difference))
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.
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 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.
from datetime import date, datetime #First Date date1 = date(2020, 2, 20) #Second Date date2 = date(2020, 3, 20) difference = date1 - date2 #Returns timedelta object print(difference) print(type(difference)) #First time datetime1 = datetime(2020, 2, 20, 10, 10, 10, 101010) #Second time datetime2 = datetime(2020, 3, 20, 15, 15, 10, 111111) difference = datetime1 - datetime2 #Returns timedelta object print(difference) print(type(difference))
You can clearly see the Negative timedelta
objects returned in the following output screenshot.
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.
from datetime import date, datetime #First Date date1 = date(2020, 2, 20) #Second Date date2 = date(2020, 3, 25) difference1 = date2 - date1 #Returns timedelta object print(difference1) print(type(difference1)) #First time datetime1 = datetime(2020, 2, 20, 10, 10, 10, 101010) #Second time datetime2 = datetime(2020, 3, 20, 15, 15, 10, 111111) difference2 = datetime2 - datetime1 #Returns timedelta object print(difference2) print(type(difference2)) #Difference between timedelta objects delta = difference2 - difference1 print(delta) print(type(delta))
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.
from datetime import timedelta timedelta_obj = timedelta(days = 25, hours = 15, minutes = 24, seconds = 33, microseconds = 222222) print(timedelta_obj)
Evaluating Seconds from timedelta
Objects
The timedelta
object contains the 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.
from datetime import timedelta timedelta_obj = timedelta(days = 25, hours = 15, minutes = 24, seconds = 33, microseconds = 222222) print(timedelta_obj.total_seconds())
Here you can see, we’ve got the timedelta
object duration in seconds.
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.
from datetime import timedelta timedelta_obj = timedelta(days = 25, hours = 15, minutes = 24, seconds = 33, microseconds = 222222) print(timedelta_obj) print(timedelta_obj*5) print(timedelta_obj*2.55)
Formatting date & time in Python
The format of the date is really important. In different countries across the world, people make use 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.
from datetime import datetime #Fetching current time time = datetime.now() #Format 1 print(time.strftime("%d/%m/%Y")) #Format 2 print(time.strftime("%H:%M:%S")) #Format 3 print(time.strftime("%d/%m/%Y %H:%M:%S"))
The different symbols that you can use for the formatting of the date and time can be found here on the website strftime.org. This method converts the datetime
object into a plain string that contains the 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 developers.
Example. In the following code, we’re converting the plain string date and time information into a datetime
object.
from datetime import datetime #String to Time date = datetime.strptime("30 March 2020", "%d %B %Y") print(date) print(type(date))
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.
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 time zones using the pytz module.
#Importing datetime from datetime import datetime #Importing pytz import pytz #Getting Local Current Time localtime = datetime.now() print(localtime) #Fetching Indian Standard Time (IST) india = pytz.timezone("Asia/Kolkata") india_time = datetime.now(india) print(india_time) #Fetching UTC Time utc = pytz.utc utc_time = datetime.now(utc) print(utc_time)
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.