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:
-
date
-
time
-
datetime
-
timedelta
-
tzinfo
-
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:
|
|
Output:
|
|
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:
|
|
Output:
|
|
- 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:
|
|
Output:
|
|
In the above example, the time() method creates a time object with the hour, minute, and second specified as arguments.
- 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:
|
|
Output:
|
|
In the above example, the datetime() method creates a datetime object with the year, month, day, hour, minute, and second specified as arguments.
- 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:
|
|
Output:
|
|
In the above example, the timedelta() method creates a timedelta object with the duration of 7 days, 12 hours, and 30 minutes.
|
|
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
- 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:
|
|
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.
|
|
Output:
|
|
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.
|
|
Output:
|
|
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.
|
|
Output:
|
|
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 | % |
|
|
Output:
|
|
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.
|
|
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.
|
|
Output:
|
|
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:
|
|
Output:
|
|
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:
|
|
Output:
|
|
The calendar.weekday()
function returns the weekday of a given date. It takes three arguments, the year, the month, and the day. For example:
|
|
Output:
|
|
The calendar.isleap()
function returns True if the given year is a leap year, otherwise False. It takes one argument, the year. For example:
|
|
Output:
|
|
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.