1.4 Date & Time Variables

Working with Variables

Working with Dates and Times

The datetime module is an essential component of Python that provides comprehensive functionality for working with dates and times. Understanding how to manipulate temporal data is crucial in data analytics, as many datasets contain time-based information that requires proper handling and analysis. The module offers several key functions that form the foundation of temporal data manipulation.

The datetime.datetime.now() function returns the current date and time as a datetime object, which is particularly useful for timestamping data or calculating time differences. When you need to create specific date objects, datetime.datetime(year, month, day) allows you to construct datetime objects with precise values. However, one of the most powerful features is datetime.strptime(date, format), which converts string representations of dates into datetime objects using a specified format pattern. The typical format string "%Y-%m-%d %H:%M:%S" represents year-month-day hour:minute:second, but the format can be customized to match various date string patterns you might encounter in real-world data. Conversely, strftime() allows you to format datetime objects back into strings with your desired appearance, giving you complete control over how dates are displayed in your analysis outputs.

Why we need date objects

Working with dates as strings presents significant challenges in data analysis and programming. When dates are stored as text, Python treats them purely as character sequences rather than temporal values, which leads to incorrect comparisons and calculations. This fundamental limitation becomes apparent when trying to perform operations that should be intuitive with dates.

Consider the example below where we attempt to compare two birth dates stored as strings. Python performs lexicographical (alphabetical) comparison on the string characters rather than interpreting them as actual dates. This means “1986-02-14” is compared character by character against “1985-04-16”, and since “1986” comes after “1985” alphabetically, Python incorrectly concludes that Nathan was born later, when in fact Rebecca is older chronologically.

from datetime import datetime  # IMPORTANT!!!! import datetime

nathan = "1986-02-14"
rebecca = "1985-04-16"

# print(datetime.now())

if nathan > rebecca:
    print("nathan came later")
else:
    print("rebecca is older")
nathan came later

The output shows Rebecca is older, but this is misleading because the comparison is based on string sorting rather than chronological order. This demonstrates why date objects are essential—they enable Python to understand temporal relationships, perform accurate date arithmetic, calculate time differences, and sort chronological data correctly. Without proper date objects, any analysis involving time series data, age calculations, or temporal comparisons would produce unreliable results.

Converting strings to datetime objects

The solution to the string comparison problem lies in converting text-based dates into proper datetime objects using the datetime module. This transformation enables Python to understand temporal relationships and perform accurate chronological operations. The process involves two key functions that work as complementary operations:

strptime() — String Parse Time: This function converts a date string into a datetime object by parsing it according to a specified format. The “p” in strptime stands for “parse,” meaning it interprets the string representation and converts it into Python’s internal datetime format. The function requires two arguments: the date string and a format code that tells Python how to interpret the string structure.

strftime() — String Format Time: This function works in the opposite direction, converting a datetime object back into a formatted string representation. The “f” stands for “format,” allowing you to control exactly how the date appears when displayed or saved. This is essential for creating human-readable output or preparing data for export.

In the example below, we use strptime() to convert our birth date strings into datetime objects, then perform the comparison using actual time calculations. Instead of comparing strings alphabetically, we calculate the time difference between the current date and each birth date to determine who is older:

n = datetime.strptime(nathan, "%Y-%m-%d")
r = datetime.strptime(rebecca, "%Y-%m-%d")

if datetime.now() - n > datetime.now() - r:
    print(f"nathan is older, he was born {datetime.strftime(n, '%B %d, %Y')}")
else:
    print(f"rebecca is older, she was born {datetime.strftime(r, '%B %d, %Y')}")

print(f"In case you were wondering that was a {r.weekday()}")
rebecca is older, she was born April 16, 1985
In case you were wondering that was a 1

The format string "%Y-%m-%d" tells Python to expect a four-digit year, followed by a hyphen, two-digit month, another hyphen, and two-digit day. When we display the results using strftime(), we use "%B %d, %Y" to format the output as “Month Day, Year” (e.g., “February 14, 1986”). This demonstrates how datetime objects enable both accurate calculations and flexible presentation of temporal data.

Weekdays return 0-6

In Python’s datetime module, days of the week are represented as integers ranging from 0 to 6, where:

  • 0: Monday
  • 1: Tuesday
  • 2: Wednesday
  • 3: Thursday
  • 4: Friday
  • 5: Saturday
  • 6: Sunday

You can retrieve the day of the week using the .weekday() method of a datetime object. For example:

days = {
    0: "Monday",
    1: "Tuesday",
    2: "Wednesday",
    3: "Thursday",
    4: "Friday",
    5: "Saturday",
    6: "Sunday",
}
r = datetime.strptime(rebecca, "%Y-%m-%d")

print(f"Rebecca was born on a {days[r.weekday()]} in {r.year}")
Rebecca was born on a Tuesday in 1985
  • Here we are accessing the name of the day off the dictionary days using the integer returned by r.weekday() (which returns an integer between 0 and 6) using bracket notation ([]), which calls the key, returning the value. This allows us to convert the integer representation of the day into a human-readable format. This method is called a hashmap or dictionary lookup, where the integer key corresponds to the day of the week, and the value is the name of that day. Hashmaps are a common technique in programming to map values to more meaningful representations.
str format Explanation
%a Weekday, short version
%A Weekday, full version
%w Weekday as a number 0-6
%d Day of month 01-31
%b Month name, short version
%B Month name, full version
%m Month as a number 01-12
%y Year, short version, without century
%Y Year, full version
%H Hour 00-23
%I Hour 00-12
%p AM/PM
%M Minute 00-59
%S Second 00-59
%f Microsecond 000000-999999
%z UTC offset
%Z Timezone

Example

print(datetime.strftime(r, "%A, %B %d, %Y"))
print(datetime.strftime(n, "%I:%M:%S %p"))
print(datetime.strftime(n, "%a, %Y, %B %d"))
Tuesday, April 16, 1985
12:00:00 AM
Fri, 1986, February 14

Time delta

A timedelta is a way to add or subtract time from a date object. It represents a duration, the difference between two dates or times. You can create a timedelta object by specifying the number of days, seconds, microseconds, milliseconds, minutes, hours, and weeks. This is useful for calculating future or past dates based on a given date. We create it by importing the timedelta class from the datetime module. Then we can create a timedelta object by specifying the duration we want to add or subtract. For example, if we want to find out what date it will be 365 days from now, we can do the following:

from datetime import timedelta, datetime

print(
    f"Is Rebecca younger if we make her brithday 365 days later? {datetime.now() - (r + timedelta(days=365)) < datetime.now() - n}"
)
Is Rebecca younger if we make her brithday 365 days later? True

What is happening here is that we are creating a timedelta object that represents 365 days. We then add this timedelta to Rebecca’s birth date, effectively moving her birthday one year into the future. Finally, we compare the adjusted date with Nathan’s birth date to see if Rebecca would be younger if her birthday were one year later.