Contents

Working with Dates and Times in Python

Learn how to create, manipulate, format, and convert datetime objects in Python using the datetime module.

Website Visitors:

Introduction to Datetime in Python

Datetime is an essential module in Python programming that deals with dates, times, and time intervals. It provides classes for working with dates and times, including date, time, datetime, timedelta, and tzinfo. The datetime module in Python allows you to perform arithmetic operations on dates and times, compare them, format them, and convert them between different time zones. This article will provide an overview of the datetime module in Python, including its classes and methods, and provide examples to demonstrate how to work with dates and times using Python.

Python Datetime Classes

The datetime module in Python provides five main classes for working with dates and times. These are:

  1. date

  2. time

  3. datetime

  4. timedelta

  5. tzinfo

  6. Date Class

The date class in Python represents a date (year, month, day) and provides methods for working with dates. You can create a date object using the date() constructor, as shown below:

1
2
3
4
from datetime import date

today = date.today()
print(today)

Output:

1
2023-05-04

In the above example, the today() method returns the current date.

You can also create a date object by specifying the year, month, and day, as shown below:

1
2
3
4
from datetime import date

d = date(2023, 5, 4)
print(d)

Output:

1
2023-05-04
  1. Time Class

The time class in Python represents a time (hour, minute, second, microsecond) and provides methods for working with time. You can create a time object using the time() constructor, as shown below:

1
2
3
4
from datetime import time

t = time(11, 30, 45)
print(t)

Output:

1
11:30:45

In the above example, the time() method creates a time object with the hour, minute, and second specified as arguments.

  1. Datetime Class

The datetime class in Python represents a date and time and provides methods for working with both. You can create a datetime object using the datetime() constructor, as shown below:

1
2
3
4
from datetime import datetime

dt = datetime(2023, 5, 4, 11, 30, 45)
print(dt)

Output:

1
2023-05-04 11:30:45

In the above example, the datetime() method creates a datetime object with the year, month, day, hour, minute, and second specified as arguments.

  1. Timedelta Class

The timedelta class in Python represents a duration or difference between two dates or times. You can create a timedelta object using the timedelta() constructor, as shown below:

1
2
3
from datetime import timedelta
td = timedelta(days=7, hours=12, minutes=30)
print(td)

Output:

1
7 days, 12:30:00

In the above example, the timedelta() method creates a timedelta object with the duration of 7 days, 12 hours, and 30 minutes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from datetime import datetime
from datetime import timedelta

today = datetime.now()
futuredate = timedelta(days=365)
print ("next year date:", today + future)

# You can also use timedelta directly in print statement like shown below. As we are using date and time values in the print statement, we have to convert it to string to print it.

print ("next year date:", str( datetime.now() + timedelta(days=365))

In above example, we are calculating the date for the next year. As we did not specify date details, it will display the same time as now, as it will be the same next year as well. To convert the d

  1. Tzinfo Class

The tzinfo class in Python represents a time zone and provides methods for working with time zones. You can create a custom time zone by subclassing the tzinfo class and overriding its methods, as shown below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from datetime import tzinfo, timedelta, datetime

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

Working with Datetime Objects in Python

Once you have created datetime objects, you can perform various operations on them, such as arithmetic operations, comparisons, formatting, and conversion between time zones. In the following sections, we will explore how to perform these operations in Python.

Arithmetic Operations

You can perform arithmetic operations on datetime objects using the timedelta class. For example, you can add or subtract a duration from a datetime object to get a new datetime object. The result will be a new datetime object that is the specified duration ahead or behind the original datetime object.

1
2
3
4
5
6
7
8
from datetime import datetime, timedelta

dt1 = datetime(2023, 5, 4, 11, 30, 45)
td = timedelta(days=7, hours=12, minutes=30)
dt2 = dt1 + td

print(dt1)
print(dt2)

Output:

1
2
2023-05-04 11:30:45
2023-05-12 00:00:45

In the above example, we created a datetime object dt1 and a timedelta object td. We then added the timedelta object to the datetime object to get a new datetime object dt2 that is 7 days, 12 hours, and 30 minutes ahead of the original datetime object dt1.

You can also subtract two datetime objects to get a timedelta object that represents the duration between them.

1
2
3
4
5
6
7
from datetime import datetime, timedelta

dt1 = datetime(2023, 5, 4, 11, 30, 45)
dt2 = datetime(2023, 5, 12, 0, 0, 45)
td = dt2 - dt1

print(td)

Output:

1
7 days, 12:30:00

In the above example, we subtracted two datetime objects dt2 and dt1 to get a timedelta object td that represents the duration between them, which is 7 days, 12 hours, and 30 minutes.

Comparisons

You can compare datetime objects using the comparison operators (<, <=, ==, !=, >=, >). When you compare two datetime objects, Python compares them in chronological order, starting with the year, then the month, day, hour, minute, and second.

1
2
3
4
5
6
7
from datetime import datetime

dt1 = datetime(2023, 5, 4, 11, 30, 45)
dt2 = datetime(2023, 5, 12, 0, 0, 45)

print(dt1 < dt2)
print(dt1 == dt2)

Output:

1
2
True
False

In the above example, we compared two datetime objects dt1 and dt2 using the comparison operators. The first comparison returns True because dt1 is earlier than dt2, and the second comparison returns False because dt1 is not equal to dt2.

Formatting

You can format datetime objects as strings using the strftime() method. The strftime() method takes a format string that specifies how the datetime should be formatted. The format string can contain special codes that are replaced with the corresponding value from the datetime object. List of all format codes are:

Usage Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without century 18
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 01-12 5
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 8
%f Microsecond 000000-999999 548513
%z UTC offset 100
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%x Local version of date 12/31/2018
%X Local version of time 17:41:00
%% A % character %

Source

1
2
3
4
5
from datetime import datetime
dt = datetime(2023, 5, 4, 11, 30, 45)
formatted_dt = dt.strftime("%Y-%m-%d %H:%M:%S")

print(formatted_dt)

Output:

1
2023-05-04 11:30:45

In the above example, we formatted a datetime object dt as a string using the strftime() method. We used the format string “%Y-%m-%d %H:%M:%S” to format the datetime as “YYYY-MM-DD HH:MM:SS”.

Conversion Between Time Zones

You can convert datetime objects from one time zone to another using the pytz library, which provides timezone database and utilities to handle time zones in Python. To use pytz, you first need to install it using pip.

1
!pip install pytz

Once you have installed pytz, you can create a timezone object using the timezone() method and then use the astimezone() method to convert a datetime object to the desired timezone.

1
2
3
4
5
6
7
8
9
from datetime import datetime
import pytz

dt = datetime(2023, 5, 4, 11, 30, 45, tzinfo=pytz.utc)
local_tz = pytz.timezone('US/Eastern')
local_dt = dt.astimezone(local_tz)

print(dt)
print(local_dt)

Output:

1
2
2023-05-04 11:30:45+00:00
2023-05-04 07:30:45-04:00

In the above example, we created a datetime object dt with a UTC timezone using the tzinfo parameter. We then created a timezone object local_tz for the US/Eastern time zone using the timezone() method. Finally, we used the astimezone() method to convert the datetime object to the US/Eastern time zone, which resulted in a new datetime object local_dt.

Calendars

Calendars are an essential tool for time management, scheduling and tracking events. Python provides several built-in modules for working with calendars, including the calendar module, the datetime module, and the dateutil module. In this article, we will explore these modules and demonstrate how to work with calendars in Python.

The Calendar Module

The calendar module in Python provides several functions for working with calendars. Some of the commonly used functions are calendar.month(), calendar.monthrange(), calendar.weekday(), and calendar.isleap().

The calendar.month() function returns a formatted string of a month’s calendar. It takes two arguments, the year and the month. For example:

1
2
3
import calendar

print(calendar.month(2023, 5))

Output:

1
2
3
4
5
6
7
      May 2023
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

The calendar.monthrange() function returns the weekday of the first day of the month and the number of days in the month. It takes two arguments, the year and the month. For example:

1
2
3
4
5
import calendar

weekday, days = calendar.monthrange(2023, 5)
print("Weekday of the first day:", weekday)
print("Number of days:", days)

Output:

1
2
Weekday of the first day: 0
Number of days: 31

The calendar.weekday() function returns the weekday of a given date. It takes three arguments, the year, the month, and the day. For example:

1
2
3
4
import calendar

weekday = calendar.weekday(2023, 5, 8)
print("Weekday:", weekday)

Output:

1
Weekday: 0

The calendar.isleap() function returns True if the given year is a leap year, otherwise False. It takes one argument, the year. For example:

1
2
3
4
import calendar

print(calendar.isleap(2023))
print(calendar.isleap(2024))

Output:

1
2
False
True

Suggested Article

If you’d like to continue reading, checkout our other article on handling exceptions in python here or browse all other topics here.

Conclusion

Datetime is an important module in Python that provides functions and classes to work with dates, times, and time intervals. In this article, we covered how to create datetime objects, perform arithmetic operations and comparisons, format datetime objects as strings, and convert between time zones. By understanding the datetime module, you can write more powerful and flexible Python programs that deal with dates and times.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.