Python is an open-source programming language used for a variety of applications today. There are so many remarkable modules and functions within Python, and if you’re a web developer or data scientist, learning these aspects is mandatory. 

 Let’s get started right away.

What is Datetime in Python? 

In the Python programming language, datetime is a single module. This means that it is not two separate data types. You can import this datetime module in such a way that they work with dates and times. datetime is a built-in Python module. Developers don’t need to install it separately. It’s right there. 

With the datetime module, you get to work with different classes that work perfectly with date and time. Within these classes, you can get a range of functions that deal with dates, times, and different time intervals. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Always remember that when you’re working on Python, date, and datetime are two separate objects. If you modify them in any way, you’re modifying the objects; not the timestamps or strings. 

Not clear? Let’s look into some examples in the next section to ease things out a bit. 

Examples of Datetime in Python 

Here are a few examples to help in the understanding of datetime in Python properly. Let’s begin. 

Example 1

Here, this example shows you how can get the current date using datetime in Python: 

# importing the datetime class

from datetime import datetime

#calling the now() function of datetime class

Now = datetime.datetime.now()

print("Now the date and time are", Now)

The output is as follows: 

Example1

Example 2 

Here is the second example. The aim is to count the difference between two different datetimes. 

#Importing the datetime class

from datetime import datetime

#Initializing the first date and time

time1 = datetime(year=2020, month=5, day=9, hour=4, minute=33, second=6)

#Initializing the second date and time

time2 = datetime(year=2021, month=7, day=4, hour=7, minute=55, second=4)

#Calculating and printing the time difference between two given date and times

time_difference = time2 - time1

print("The time difference between the two times is", time_difference)

And the output is: 

Example2

What is the Import Datetime Statement? 

If you’re planning to import datetime in Python, do remember this one thing - it is pretty simple. Say, you want to import a particular class like date, time, datetime, timedelta, etc. from the datetime module, here’s how it can be done: 

# importing the date class 

from datetime import date 

# importing the time class 

from datetime import time

# importing the datetime class 

from datetime import datetime

What are the Commonly Used Classes in the Datetime Module? 

There are 6 main classes when it comes to datetime in Python. Keep reading to find out more about them in this section: 

Date 

By date, we mean the conventional concept of dates with effect to the Gregorian Calander. Very naturally, the date class in Python is explained with the attributes like day, month, and year. 

Time 

The next class that is discussed here is called time. This class is independent of any day. Here it is generally assumed that each day has 24*60*60 seconds. The attributes of the time class in Python include minute, second, microsecond, hour, and tzinfo. 

Wondering what tzinfo even is? We’ll get to that in this section itself, shortly. 

Datetime 

datetime in Python is the combination between dates and times. The attributes of this class are similar to both date and separate classes. These attributes include day, month, year, minute, second, microsecond, hour, and tzinfo. 

Timedelta 

You can think of timedelta as the variation between two different dates, time, or datetime examples to microsecond resolution. 

Tzinfo 

tzinfo is nothing but an attribute. It can provide you different timezone-related information objects. 

Timezone 

Finally, it’s time to learn about the timezone class. This class can deploy the tzinfo abstract base class in terms of a fixed offset from the UTC. Here, you are looking into the new UTC version 3.2. 

What Are the Various Functions Available Within Date Class? 

Hopefully, by now, you have developed a distinctive idea on the concept of datetime in Python and date class. So, now the question is, do you know about the different functions available within the date class? 

Let’s see this in detail. 

When any particular object within the date class is embodied, the date format is represented in this way - YYYY-MM-DD. Hence, a syntax of this particular class requires three specific arguments viz. year, month, and day. 

Check the following examples:  

Example 1: Date Object to Represent a Date 

Your arguments should be in the range mentioned below: 

  • Year must be between MINYEAR and MAXYEAR 
  • The month should be between 1 to 12 
  • The day should be between 1 to the number of days in a month or year 

# Explaining date class 

# importing the date class 

from datetime import date 

# initializing syntax with arguments in the format year, month, date 

Date = date(2021, 7, 4) 

print("Date is", Date) 

Here’s the output: 

Example1_2

Please note that whenever there is any anomaly while passing any argument, Python will raise ValueError. 

Example: There are 31 days in May (5th month). If Python gets an argument like a date(2021, 5, 32) it will show an error. Also, the arguments should be integer only. Otherwise, it will show TypeError if it gets any string or float as an argument. 

Example 2: Get Current Date 

While working with datetime in Python, one can create a date object that contains the current date with the help of a classmethod. It is named ‘today()’. You can print components like the year, month, and date of today separately. In that case, you’ll need to call an individual agent. 

# To print current date 

# importing the date class 

from datetime import date 

# calling the today() function of date class 

Today = date.today() 

print("Today's date is", Today) 

print("Today’s components are", today.year, today.month, today.day) 

Here’s the output: 

Example2_2

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3: Get Date From a Timestamp 

Did you know that creating dateobjects from a timestamp is also possible? Think of a Unix Timestamp. It is basically the number of seconds between any specific date and January 1, 1970, at UTC. Converting a timestamp is also possible. But in that case, you have to use the fromtimestamp() method. 

# To get timestamp from a date

# importing the date class 

from datetime import date

Timestamp = date.fromtimestamp(1000000000)

print("Date is", timestamp)

Here’s the output:

 Example3_2

How Can You Handle Timezones in Python? 

Let’s say that you’re working on a technical project at the moment. You’ve to display the dates in the timezone of your clients. Handling timezone by yourself can be a big deal. When working with datetime in Python, why not use a third-party pytz module? 

See the below examples for more clarity: 

#To get the local time of specific place

from datetime import datetime

#Importing third-party module pytZ

import pytz

#Calling local time

Local_datetime = datetime.now()

print("Local date is", Local_datetime)

#Calling local time of Toronto

Timezone_Toronto = pytz.timezone('America/Toronto') 

Local_datetime_Toronto = datetime.now(Timezone_Toronto)

print("The date and time in Toronto is",Local_datetime_Toronto)

#Calling local time of Tokyo

Timezone_Tokyo = pytz.timezone('Asia/Tokyo') 

Local_datetime_Tokyo = datetime.now(Timezone_Tokyo)

print("The date and time in Tokyo is",Local_datetime_Tokyo)

Here’s the output: 

Example4_2

Conclusion 

With this, you have come to the end of this ‘datetime in Python’ tutorial. Python is today, one of the most widely used languages with widespread applications in cutting-edge areas like data science and analytics. If you are looking to build a career in data science, python is an essential skill you’d have to possess. Simplilearn’s Data Science with Python Certification Course is an excellent way for you to acquire all the skills you need to embark on the journey to becoming a data scientist. With 68 hours of applied learning sessions featuring 4 real-life projects to practice and perfect your skills, this program will offer your work-ready training in the fundamentals of data analysis, data visualization, web scraping, machine learning & natural language processing. Do explore the course at the earliest and get started.

We hope you found this ‘datetime in Python’ tutorial, useful. Check out our next tutorial on Random number in python. If you still have any questions on the topic, don’t hesitate to let us know your questions in the comments section below. Our team of SMEs will review them and respond at the earliest.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449