Future-Proof Your Career, Master Data Skills + AI

Blog

Future-Proof Your Career, Master Data Skills + AI

Python Datetime: A Comprehensive Guide With Examples

by | 7:08 pm EDT | May 24, 2023 | Python

When working with data projects in Python, you are most likely to use datetime functions. Almost every dataset that you’ll work with will have a datetime column that you’ll want to manipulate according to your needs and project requirements.

Luckily, Python comes with its own built-in module named datetime that allows you to represent, manipulate, and perform operations with datetime instances such as dates, times, and combinations of the two. Mastering the Python datetime module will help you make more robust time-series analyses in your projects.

The Python datetime module is a tool for handling dates, times, and time intervals. It allows you to perform various operations on dates and times in a straightforward manner.

Python datetime
Programming abstract – source code and binary code on display of software developer. Black theme with colored syntax.

By using the datetime module in Python, you can easily work with date and time values, manage time zones, perform calculations, and even handle formatting and parsing for various representations. This functionality make the datetime module an essential tool in many applications, from data processing to event scheduling and beyond.

Before you get started using Python’s datetime module in your projects, it is crucial to understand its underlying classes. In the section below, we will look at the five main classes of Python’s DateTime module. Let’s get into it!

What are the 5 Main Classes of Python Datetime Module?

The Python Datetime module is a part of the standard library that provides classes to manipulate and work with dates, times, timezones, and durations.

The module consists of five main classes:

  1. Datetime

  2. Date,

  3. Time,

  4. Timedelta

  5. Timezone.

    We will look at each class followed by an example use cases to help you better understand the concept.

How to Use the Datetime Class

The Python Datetime class is the most commonly used class in the module. It represents a single point in time with attributes like year, month, day, hour, minute, second, and microsecond.

Some common operations with the Python Datetime class include:

  • datetime.datetime.now()

This function allows you to get the current date and time. The following is an example of retrieving the current date and time:

import datetime

# Get the current date and time
now = datetime.datetime.now()

print("Current date and time: ", now)

This will output the current date and time at the moment of execution in the format YYYY-MM-DD HH:MM:SS.ssssss.

Retrieving the current date and time in Python
  • datetime.datetime

This function allows you to create a custom date and time object. The following is an example of using datetime.datetime in your code:

from datetime import date

# Create a custom date and time object
custom_date = datetime.datetime(2023, 5, 22, 17, 40)

print("Custom date and time: ", custom_date)

In addition to the above functions, the Datetime class also provides methods for working with date and time such as:

Creating a custom date and time object in python code
  • strftime():

The method allows you to format the date and time objects as a string. The following is an example of strftime() method:

import datetime

# Create a custom date and time object
custom_date = datetime.datetime(2023, 5, 22, 17, 40)

# Format the datetime object as a string
formatted_date = custom_date.strftime("%B %d, %Y, %H:%M")

print("Formatted date and time: ", formatted_date)

This code will convert datetime object to a string:

Formatting the datetime object as string
  • strptime():

This function in the datetime class allows you to parse a string representing date and time objects into a single Datetime object. The following is an example of parsing a date stored as a string to a Datetime object:

import datetime

# String representing a date and time
date_string = "May 22, 2023, 17:40"

# Parse the string into a datetime object
parsed_date = datetime.datetime.strptime(date_string, "%B %d, %Y, %H:%M")

print("Parsed date and time: ", parsed_date)

This will convert the string into a DateTime object.

Parsing a string into a datetime object

How to Use the Date Class

The Date class allows you to deal exclusively with date objects(year, month, and day). You can create date objects with the date class.

Some common operations with the Date class include:

  • datetime.date.today()

This function in the date class allows you to get the current date. The following is an example of retrieving the current date with the date class:

import datetime

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

print("Today's date: ", today)

This Python code will output the current date at the moment of execution in the format YYYY-MM-DD.

Retrieving the current date

At the time of writing this article, the current date was 2023-05-22.

  • datetime.date()

This function in the date class allows you to create date objects. The example demonstrates creating a custom date object with datetime.date() function:

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

print("Custom date: ", custom_date)

In the datetime.date() function, you provide the year, month, and day as arguments.

This script will output 2023-05-22, as you’ve created a custom date object for the date May 22, 2023.

Creating a custom date object in python

The Date class also provides useful methods, such as:

  • weekday()

This method in the date class returns the day of the week (0 for Monday, 1 for Tuesday, etc.). The following example demonstrates the weekday() method:

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Get the day of the week
day_of_week = custom_date.weekday()

print("Day of the week: ", day_of_week)

In this example, custom_date.weekday() will return 0 because May 22, 2023, falls on a Monday.

Retrieving the current day of the week
  • strftime()

This method in the date class allows you to format the date object as a string. The following example demonstrates strftime() function:

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Format the date object as a string
formatted_date = custom_date.strftime("%B %d, %Y")

print("Formatted date: ", formatted_date)

This will output the date formatted as “Month day, Year”.

Formatting the date object as a string
  • strptime()

This method allows you to parse a string representing a date into a Date object. The following is an example of converting a string date into a Date object:

import datetime

# String representing a date
date_string = "May 22, 2023"

# Parse the string into a date object
parsed_date = datetime.datetime.strptime(date_string, "%B %d, %Y").date()

print("Parsed date: ", parsed_date)

This will output the date object created from the date string.

Parsing a string into a date object

How to Use the Time Class

The Time class allows you to work with time instances (hour, minute, second, microsecond). With the time class, you can create a custom time object with datetime.time().

The following example demonstrates creating a custom time object:

import datetime

# Create a custom time object
custom_time = datetime.time(17, 40)

print("Custom time: ", custom_time)

In the datetime.time() function, you provide the hour and minute as arguments.

This script will output 17:40:00, as specified in the Python code.

Creating a custom time object in python code

The Time class provides useful methods, such as:

  • strftime()

This method allows you to format the time object as a string. Below is an example of this function:

import datetime

# Create a custom time object
custom_time = datetime.time(17, 40)

# Format the time object as a string
formatted_time = custom_time.strftime("%H:%M")

print("Formatted time: ", formatted_time)

This will output the local time formatted as “Hour:Minute”.

Formatting a time object as a string
  • strptime()

This function allows you to parse a string representing time into a Time object. The following example demonstrates this function:

from datetime import time

# String representing a time
time_string = "17:40"

# Parse the string into a time object
parsed_time = datetime.datetime.strptime(time_string, "%H:%M").time()

print("Parsed time: ", parsed_time)

This will output the time objects created from the time string.

Parsing a string into a time object

How to Use The Timedelta Class

The Timedelta class allows you to represent represents a duration or difference between two dates or times.

With Timedelta class, you can perform the following operations:

  • Calculate the difference between two dates or times

An example of calculating the difference between two dates is given below:

 import datetime

# Create two custom date objects
date1 = datetime.date(2023, 5, 22)
date2 = datetime.date(2023, 6, 1)

# Calculate the difference between the two dates
date_difference = date2 - date1

print("Difference between the dates is: ", date_difference.days, "days")

In this example, date_difference is a timedelta object representing the difference between date2 and date1. The .days property gives the number of days between the two dates.

Calculating the difference between the two dates
  • Add or subtract a duration to a date or time

An example of adding a duration to a date is given below:

import datetime

# Create a custom date object
custom_date = datetime.date(2023, 5, 22)

# Create a duration of 10 days
duration = datetime.timedelta(days=10)

# Add the duration to the date
new_date = custom_date + duration

print("New date: ", new_date)

In this example, duration is a timedelta object representing a duration of 10 days. We use the + operator to add this duration to custom_date.

Adding a duration to a date object

How to Use the Timezone Class

The Timezone class allows you to handle time zones and daylight saving time adjustments.

You can perform the following operation with timezone class:

  • Create a timezone object

To create a timezone object, you can use the datetime.timezone() function. The following example demonstrates creating a timezone object:

import datetime

# Create a timezone object for a timezone 2 hours ahead of UTC
two_hours_ahead = datetime.timezone(datetime.timedelta(hours=2))

print("Timezone object: ", two_hours_ahead)

In this example, two_hours_ahead is a timezone object representing a timezone that is 2 hours ahead of Coordinated Universal Time (UTC).

This script will output a timezone object like <UTC+02:00>.

Creating a timezone object for a timezone
  • Object with a specific timezone

To achieve this, you can use the .replace(tzinfo=tz) function. The following example demonstrates this function:

import datetime

# Create a naive datetime object
naive_datetime = datetime.datetime(2023, 5, 22, 17, 40)

# Create a timezone object for a timezone 2 hours ahead of UTC
two_hours_ahead = datetime.timezone(datetime.timedelta(hours=2))

# Convert the naive datetime object to an aware object
aware_datetime = naive_datetime.replace(tzinfo=two_hours_ahead)

print("Aware datetime object: ", aware_datetime)

In this example, naive_datetime is a datetime object that does not have any timezone information. The two_hours_ahead variable is a timezone object representing a timezone that is 2 hours ahead of UTC.

The replace(tzinfo=two_hours_ahead) method is used to create a new datetime object with the same date and time as naive_datetime, but with tzinfo set to two_hours_ahead.

Converting a naive datetime object to an aware datetime

The Timezone helps you maintain accurate and consistent time values when working with data that spans multiple time zones.

You have gone through some of the most important functions in the datetime module in Python. In the next section we will implement some of the above functions to a case studywhich will give you a practical look into the implementation of these datetime module in your projects.

Implementing the DateTime Module Functions to a Case Study

Let’s consider a case study where we are given a dataset of different events that happened around the world. The dataset has corresponding dates and times in a string format.

Our task is to transform these dates and times into DateTime objects and perform operations on them as needed.

Suppose we are given the following dataset:

Dateset under analysis

If we check the data types of the variable we will see that date and time are stored as a string. Therefore, before carrying out any analysis, we have to convert the date and time columns to a suitable format.

To do this, we can use the following code:

import datetime

# Convert 'Date' and 'Time' strings into datetime objects
df['DateTime'] = df['Date'] + ' ' + df['Time']
df['DateTime'] = df['DateTime'].apply(lambda x: datetime.datetime.strptime(x, "%b %d, %Y %H:%M"))

print(df)

In this block of code, we first create a new column ‘DateTime’ in your DataFrame by concatenating the ‘Date’ and ‘Time’ columns. Then, we apply the datetime.strptime function to each value in this new column to convert the date and time strings into datetime objects. Finally, we print out the DataFrame to see the result.

Converting Date and Time strings into datetime objects

The next thing we would like to do is to calculate the difference between two events. To do this we can use the following code:

duration = df.loc[1, 'DateTime'] - df.loc[0, 'DateTime']
print("Duration between Event1 and Event2: ", duration)

This Python script will calculate the duration between ‘Event1’ and ‘Event2.

Calculating duration between two events

Finally, let’s convert the datetime objects into a different timezone. When can achieve this using the Timezone functions in the datetime module.

# Create a timezone object for UTC
utc_tz = datetime.timezone(datetime.timedelta(0))

# Convert the datetime objects into UTC
df['DateTime_UTC'] = df['DateTime'].apply(lambda x: x.replace(tzinfo=utc_tz))

print(df)

In this code, we create a timezone object for UTC. Next, we create a new column in our DataFrame named ‘DateTime_UTC’ by applying a lambda function to our ‘DateTime’ column. This will replace the timezone information of each datetime object with UTC.

Converting datetime objects into UTC

Through the above example case study, you see how the various functions provided by DateTime module work together to manipulate dates and times to a suitable format.

Now that you are familiar with some of the functions in the datetime module, let’s go ahead and look at a few additional functions that you’ll want to use as you take on more complex projects.

Apart from the functions listed above, there are many more useful functions that you can use depending on the problem at hand. Python developers often keep a documentation page open to look for functions that can cater to your needs. And we suggest you do the same!

Additional Date and Time Functions

In this section, we will discuss additional functions in the Python datetime module. This includes retrieving weekdays, month and weekday names, along with the ctime() function.

How to Retrieve Weekdays From a Date

The datetime module comes with a weekday() function, which returns the day of the week as an integer (where Monday is 0 and Sunday is 6).

To use this function, you can call it on a date or datetime object.

import datetime

today = datetime.date.today()
weekday_number = today.weekday()

print(weekday_number)

The output of the above code is given in the image below:

Retrieving weekdays from a date in python code on computer

The current local date is 5/23/2023 and the weekday is Monday.

How to Retrieve Month and Weekday Names From a Date

datetime also allows you to retrieve the name of the month and the day of the week.

You can use the strftime() function, which formats a date or datetime object as a string.

The following is an example of how to use the strftime() function to get the name of the month and the day of the week:

import datetime

today = datetime.date.today()
weekday_name = today.strftime('%A')
month_name = today.strftime('%B')

print(weekday_name)
print(month_name)

This code will print the weekday name and month name in the output.

Retrieving weekday name and month name

How to Use the Ctime Function

The ctime() function in the datetime module returns a string representation of a date or datetime object, formatted as “Day Mon DD HH:MM:SS YYYY.

ctime is a method for a datetime object, not a stand-alone function.

The following is an example of using ctime function in your code:

import datetime

now = datetime.datetime.now()
formatted_date = now.ctime()

print(formatted_date)

The above code will return a string representation of the date object.

String representation of a date object

To learn more about working with time-series data, take a look at the following video:

Final Thoughts

As a Python programmer, mastering the datetime module is important. It’s a toolkit that enables you to deal with dates, times, and time intervals. These are the elements you’ll frequently encounter in real-world data.

You’ll need this module to convert strings into datetime objects, handle timezone conversions, and perform operations on dates and times.

By learning how to use datetime module, you’ll be better prepared to handle these tasks in your own projects!

Related Posts