python tutorial

Python Datetime Module

Learn more about Python, one of the world’s most versatile and popular programming languages.

Python provides a huge collection of built-in modules that can be readily used while writing code in Python. A module is basically a collection of useful classes and each class has attributes and methods available for use. This helps developers to not reinvent the wheel for common tasks and focus on the big picture implementation. One such module that is quite useful is Datetime.

The Datetime module provides a collection of useful methods for working with date and time in Python. Let’s dive into this module and all the features it provides.

Some of the most common tasks you can do with datetime module are:

  • Get current date and time
  • Create new date if year, month and day are known
  • Create time object if hour, minute, second is known
  • Get date and time if Unix timestamp is known

We have barely touched the surface with these common tasks. Datetime is a great module with many other amazing features that comes handy for various tasks around date and time in Python.

Any built-in Python module can be used by first importing it at the top of the file using the import keyword.

Let’s see how to use the datetime module and its built-in features in Python.

Code Example
# import datetime module
>>> import datetime
# use now method of datetime class in datetime module
>>> datetime_obj = datetime.datetime.now()
>>> print(datetime_obj)
2022-05-11 16:41:36.541131
# use today method of date class in datetime module
>>> date_obj = datetime.date.today()
>>> print(date_obj)
2022-05-11
# use time class in datetime module
>>> time_hour_obj = datetime.time(11,59, 30)
>>> print(time_hour_obj)
11:59:30

A datetime object can also be created manually by specifying year, month, day, hour, minute, seconds and timestamp or a combination of these values. You can also find the difference between two time objects using timedelta.

Code Example
>>> from datetime import datetime, date

>>> t1 = date(year = 2021, month = 11, day = 12)
>>> t2 = date(year = 2020, month = 6, day = 12)
>>> t3 = t1 - t2
>>> print("t3 =", t3)
t3 = 518 days, 0:00:00

>>> t4 = datetime(year = 2021, month = 5, day = 14, hour = 9, minute = 13, second = 35)
>>> t5 = datetime(year = 2019, month = 4, day = 8, hour = 3, minute = 52, second = 18)
>>> t6 = t4 - t5
>>> print("t6 =", t6)
t6 = 767 days, 5:21:17

Learn Python Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required