Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

datetime Program in Python

Last Updated on December 26, 2023 by Ankit Kochar

Dealing with date and time in software development is a common yet intricate task. Python offers a robust datetime module, empowering developers to manipulate dates, times, and intervals efficiently within their programs. Understanding and leveraging Python’s datetime functionalities can significantly enhance the precision and flexibility of applications involving time-related operations.

This article aims to explore Python’s datetime module comprehensively. From handling dates, times, timezones to performing calculations and formatting, this guide will provide an in-depth understanding of utilizing datetime in Python programming.

Main Classes of the datetime Module

There are mainly 6 classes of datetime module present, which are listed below:

  1. date class: The date class is a part of the datetime module in Python, and represents a date (year, month, and day).
  2. time class: The time class is another class provided by the datetime module in Python, and represents a time of day (hours, minutes, seconds, and microseconds).
  3. datetime class: The datetime class is one of the most important classes provided by the datetime module in Python. It represents a combination of a date and a time and provides a range of methods to manipulate and work with date-time values.
  4. timedelta class: The timedelta class is another class provided by the datetime module in Python. It represents a duration of time (days, seconds, and microseconds) and can be used to perform arithmetic operations on date-time values.
  5. tzinfo class: The tzinfo class is a base class in the datetime module that can be used to define time zones for date-time objects. It is an abstract base class, which means that you cannot instantiate it directly, but you can subclass it to create your own time zone classes.
  6. timezone class: The timezone class is a subclass of tzinfo class in the datetime module that represents a fixed offset from UTC (Coordinated Universal Time). It is a simpler way to work with time zones compared to using a custom tzinfo class.

Date Class of datetime Module

Python uses the date class to create date objects. A date in the format YYYY-MM-DD is represented by an object of this class when it is instantiated. Year, Month and Date is required to construct date class.

Syntax of the date class:

datetime.date(year, month, day)

Let’s take an example of date class.

import datetime

# Create a date object for January 1, 2023
d = datetime.date(2023, 1, 1)
print(d)  

# Get the current date
today = datetime.date.today()
print(today) 

# Get the year, month, and day of a date object
year = today.year
month = today.month
day = today.day
print(year, month, day)  # print each value separately

# Format a date object as a string
date_string = today.strftime("%d/%m/%Y")
print(date_string) 

# Parse a date string into a date object
date_string = "2023-03-15"
parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d").date()
print(parsed_date) 

# Get the day of the week as an integer (Monday is 0 and Sunday is 6)
weekday = today.weekday()
print(weekday)

Output:

2023-01-01
2023-03-15
2023 3 15
15/03/2023
2023-03-15
2

Time Class of datetime Module

The time class of the datetime module is used to display time of the day including hours, minutes, seconds, and microseconds.

Syntax of the time class:

datetime.time(hour, minute, second, microsecond, tzinfo, fold)

Let’s take an example of time class.

import datetime

# Create a time object for 9:30 AM
t = datetime.time(9, 30)
print(t)  

# Get the current time
now = datetime.datetime.now()
current_time = now.time()
print(current_time)  

# Get the hour, minute, and second of a time object
hour = t.hour
minute = t.minute
second = t.second
print(hour, minute, second)  # print each value separately

# Format a time object as a string
time_string = t.strftime("%I:%M %p")
print(time_string)  

# Compare two time objects
time1 = datetime.time(8, 30)
time2 = datetime.time(9, 30)
if time1 < time2:
    print("time1 is earlier than time2")
else:
    print("time1 is late than time2")

Output:

09:30:00
08:18:22.140074
9 30 0
09:30 AM
time1 is earlier than time2

Datetime Class of datetime Module

The datetime class is the combination of the above two classes a date and a time. The datetime class also provides a range of methods to manipulate and work with date-time values.

Syntax of the datetime class:

datetime.datetime(year, month, day, hour, minute, second, microsecond, tzinfo, fold)

Let’s take an example of the datetime class.

import datetime

# Create a datetime object for January 1, 2023 at 9:30 AM
dt = datetime.datetime(2023, 1, 1, 9, 30)
print(dt)  # 2023-01-01 09:30:00

# Get the current datetime
now = datetime.datetime.now()
print(now)  # current datetime in the format yyyy-mm-dd hh:mm:ss.microseconds

# Get the year, month, day, hour, minute, and second of a datetime object
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(year, month, day, hour, minute, second)  # print each value separately

# Format a datetime object as a string
datetime_string = now.strftime("%Y-%m-%d %H:%M:%S")
print(datetime_string)  # formatted datetime string

# Parse a datetime string into a datetime object
datetime_string = "2023-03-15 14:30:00"
parsed_datetime = datetime.datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")
print(parsed_datetime)  # 2023-03-15 14:30:00

# Create a timedelta object representing a duration of time
delta = datetime.timedelta(days=7)
new_date = now + delta
print(new_date)  # current date + 7 days

# Get the difference between two datetime objects
dt1 = datetime.datetime(2022, 1, 1, 9, 30)
dt2 = datetime.datetime(2023, 1, 1, 9, 30)
delta = dt2 - dt1
print(delta.days)  # number of days between the two datetime objects

Output:

2023-01-01 09:30:00
2023-03-15 08:33:49.745378
2023 3 15 8 33 49
2023-03-15 08:33:49
2023-03-15 14:30:00
2023-03-22 08:33:49.745378
365

Timedelta Class of the datetime Module

Python’s timedelta class is used to determine when two dates are different and can also be used to manipulate dates. The timedelta class can also be used to perform arithmetic operations on date-time values.

Syntax of the timedelta class:

datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)

Let’s see an example of the timedelta class.

import datetime

# Create a timedelta object representing a duration of time
delta = datetime.timedelta(days=7, hours=2, minutes=30)
print(delta)  

# Add a timedelta to a datetime object
dt = datetime.datetime(2023, 3, 15, 14, 30)
new_dt = dt + delta
print(new_dt)  

# Subtract a timedelta from a datetime object
dt = datetime.datetime(2023, 3, 15, 14, 30)
new_dt = dt - delta
print(new_dt)  

# Create a timedelta from the difference between two datetime objects
dt1 = datetime.datetime(2023, 3, 8, 12, 0)
dt2 = datetime.datetime(2023, 3, 15, 14, 30)
delta = dt2 - dt1
print(delta)  

# Convert a timedelta to seconds
delta = datetime.timedelta(hours=2, minutes=30)
total_seconds = delta.total_seconds()
print(total_seconds)

Output:

7 days, 2:30:00
2023-03-22 17:00:00
2023-03-08 12:00:00
7 days, 2:30:00
9000.0

Tzinfo Class of the datetime Module

The tzinfo class of the datetime module is used to define the time zones for the datetime modules.

Let’s take an example of the tzinfo class.

import datetime

class EST(datetime.tzinfo):
    def utcoffset(self, dt):
        return datetime.timedelta(hours=-5)
    def dst(self, dt):
        return datetime.timedelta(0)
    def tzname(self, dt):
        return "EST"

# Create a datetime object in the EST time zone
dt = datetime.datetime(2023, 3, 15, 14, 30, tzinfo=EST())
print(dt)  

# Get the current time in the EST time zone
now = datetime.datetime.now(tz=EST())
print(now)  

# Convert a datetime object to a different time zone
dt = datetime.datetime(2023, 3, 15, 14, 30, tzinfo=EST())
utc_dt = dt.astimezone(datetime.timezone.utc)
print(utc_dt)

Output:

2023-03-15 14:30:00-05:00
2023-03-15 03:54:58.600322-05:00
2023-03-15 19:30:00+00:00

Timezone class of the datetime module:

When displaying time according to a particular region’s timezone, DateTime’s timezones feature can be used. It is a simpler way to work with time zones compared to using a custom tzinfo class.

Let’s take an example of the timezone class.

import datetime

# Create a timezone object representing Pacific Standard Time (UTC-8)
pst = datetime.timezone(datetime.timedelta(hours=-8))

# Create a datetime object with the current date and time in the Pacific time zone
now = datetime.datetime.now(tz=pst)
print(now)  

# Convert a datetime object to a different time zone
utc_now = now.astimezone(datetime.timezone.utc)
print(utc_now) 

Output:

2023-03-15 01:01:03.168324-08:00
2023-03-15 09:01:03.168324+00:00

Conclusion
Python’s datetime module serves as a powerful tool for managing date and time-related functionalities within applications. Whether it’s parsing dates, performing arithmetic operations, or handling timezones, mastering datetime empowers developers to create more accurate, efficient, and versatile programs.

As you delve deeper into Python development, grasping the nuances of the datetime module will prove invaluable. Its versatility and functionality enable the creation of robust applications across various domains, from web development to data analysis and beyond.

Continual exploration and utilization of Python’s datetime capabilities allow developers to streamline time-related operations, ensuring the reliability and accuracy of their software.

FAQs Related to the datetime module in Python

Here are some FAQs related to datetime Program in Python.

1. How do I convert a string to a datetime object in Python?
You can use the strptime() method of the datetime class to parse a string and convert it to a datetime object. This method takes a format string that specifies the format of the input string. For example, to convert the string "2023-03-15 14:30:00" to a datetime object, you can use the format string "%Y-%m-%d %H:%M:%S".

2. How do you get the current date and time using Python’s datetime?
To retrieve the current date and time, you can use the datetime class from the datetime module along with the now() method. For example:

from datetime import datetime
current_date_time = datetime.now()

3. Can Python’s datetime module handle timezones?
Yes, Python’s datetime module includes time zone support through the timezone class. It allows developers to work with different timezones, convert between timezones, and manage daylight saving time.

4. How can I perform arithmetic operations on dates using Python’s datetime?
Python’s datetime module enables arithmetic operations on dates and times. For instance, you can calculate differences between dates, add or subtract time intervals using timedelta objects, and perform various arithmetic operations conveniently.

5. How do I format dates and times using Python’s datetime?
Python’s datetime module provides the strftime() method, allowing developers to format dates and times into custom string representations based on specified format codes. Conversely, the strptime() method parses strings into datetime objects based on specified formats.

6. Are there any third-party libraries for handling dates and times in Python?
Yes, there are several third-party libraries like Arrow, Pendulum, and Dateutil that offer additional functionalities and easier APIs for handling dates, times, and timezones in Python. These libraries extend the capabilities provided by the datetime module.

Leave a Reply

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