Skip to content

Python 3 - Date & Time

Handling dates and times is a common task in programming. Python provides powerful built-in modules like datetime, time, and calendar to manage date and time operations effectively, including formatting and time zone conversions.

Computers often represent a specific point in time as a single number: the total number of seconds that have passed since a reference point called the ‘epoch’. For Unix-based systems (including Linux and macOS) and often Windows, the epoch is January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC).

Python’s time module provides the time.time() function, which returns the current time as a floating-point number representing seconds since the epoch. This is often called a ‘Unix timestamp’.

#!/usr/bin/env python3
import time
# Get the current timestamp (seconds since the epoch)
current_timestamp = time.time()
print(f"Seconds since January 1, 1970: {current_timestamp}")

This output will be a large number that increases every second:

Seconds since January 1, 1970: 1678886400.123456

While timestamps are useful for calculations and storage, they are not easily human-readable. Also, note that while timestamps based on 32-bit integers had limitations (the ‘Year 2038 problem’), modern systems typically use 64-bit representations, greatly extending the representable time range.

The datetime Module: The Preferred Approach

Section titled “The datetime Module: The Preferred Approach”

For most date and time manipulations, the datetime module is more intuitive and powerful than the time module. It provides classes for working with dates, times, and time intervals.

  • datetime.date: Represents a date (year, month, day).
  • datetime.time: Represents a time (hour, minute, second, microsecond).
  • datetime.datetime: Represents both date and time.
  • datetime.timedelta: Represents a duration or difference between two dates or times.
  • datetime.timezone: Represents time zone information (further enhanced by the zoneinfo module in Python 3.9+).

Example: Getting the Current Date and Time

Section titled “Example: Getting the Current Date and Time”
#!/usr/bin/env python3
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")
# Get the current date only
today = datetime.date.today()
print(f"Current date: {today}")
# Create a specific date
specific_date = datetime.date(2024, 3, 15)
print(f"Specific date: {specific_date}")

Output:

Current date and time: 2024-03-15 10:30:00.123456
Current date: 2024-03-15
Specific date: 2024-03-15

Often, you need to display dates and times in a specific format. The strftime() method formats a datetime object into a string, while strptime() parses a string into a datetime object based on a format code.

#!/usr/bin/env python3
import datetime
now = datetime.datetime.now()
# Format examples
print(f"Standard format: {now}")
print(f"MM/DD/YY: {now.strftime('%m/%d/%y')}")
print(f"Full month name, day, year: {now.strftime('%B %d, %Y')}")
print(f"Time (HH:MM:SS): {now.strftime('%H:%M:%S')}")
print(f"Date and Time (ISO 8601): {now.isoformat()}") # Standard format

Output (example):

Standard format: 2024-03-15 10:45:12.123456
MM/DD/YY: 03/15/24
Full month name, day, year: March 15, 2024
Time (HH:MM:SS): 10:45:12
Date and Time (ISO 8601): 2024-03-15T10:45:12.123456

You can find a complete list of formatting codes in the Python documentation: strftime() and strptime() Format Codes.

Handling time zones correctly is crucial for many applications. Python 3.9 introduced the zoneinfo module, which uses the system’s IANA time zone database. For older Python versions or complex scenarios, the third-party pytz library was commonly used.

#!/usr/bin/env python3
import datetime
# zoneinfo requires Python 3.9+ and the tzdata package on some systems
# pip install tzdata
from zoneinfo import ZoneInfo
# Get current time in UTC
utc_now = datetime.datetime.now(datetime.timezone.utc)
print(f"UTC Time: {utc_now}")
# Convert to a specific time zone
ny_tz = ZoneInfo("America/New_York")
ny_now = utc_now.astimezone(ny_tz)
print(f"New York Time: {ny_now}")
# Create a timezone-aware datetime directly
london_time = datetime.datetime(2024, 3, 15, 12, 0, 0, tzinfo=ZoneInfo("Europe/London"))
print(f"London Time: {london_time}")

Output (example):

UTC Time: 2024-03-15 15:05:30.123456+00:00
New York Time: 2024-03-15 11:05:30.123456-04:00
London Time: 2024-03-15 12:00:00+00:00

Note: Time zone rules (like Daylight Saving Time) are complex and change. Using zoneinfo or a reliable library like pytz helps manage this complexity.

Working with the time Module (Lower-Level)

Section titled “Working with the time Module (Lower-Level)”

While datetime is generally preferred, the time module provides lower-level functions, often interacting directly with the OS time capabilities. It uses a representation called struct_time.

Several functions in the time module return or manipulate time as a time.struct_time object. This is essentially a named tuple containing 9 elements:

IndexAttributeFieldValues
0tm_yearYeare.g., 2024
1tm_monMonth1 to 12
2tm_mdayDay1 to 31
3tm_hourHour0 to 23
4tm_minMinute0 to 59
5tm_secSecond0 to 61 (60/61 for leap seconds)
6tm_wdayDay of Week0 to 6 (Monday is 0)
7tm_ydayDay of Year1 to 366
8tm_isdstDaylight Savings0 (No), 1 (Yes), -1 (Unknown)

Example: Getting Local Time as struct_time

Section titled “Example: Getting Local Time as struct_time”
#!/usr/bin/env python3
import time
# Get current timestamp
current_timestamp = time.time()
# Convert timestamp to local struct_time
local_time_struct = time.localtime(current_timestamp)
print(f"Local time (struct_time): {local_time_struct}")
# Access specific fields
print(f"Year: {local_time_struct.tm_year}")
print(f"Hour: {local_time_struct.tm_hour}")
# Convert timestamp to UTC struct_time
gmt_time_struct = time.gmtime(current_timestamp)
print(f"UTC time (struct_time): {gmt_time_struct}")

Output (example):

Local time (struct_time): time.struct_time(tm_year=2024, tm_mon=3, tm_mday=15, tm_hour=11, tm_min=10, tm_sec=5, tm_wday=4, tm_yday=75, tm_isdst=1)
Year: 2024
Hour: 11
UTC time (struct_time): time.struct_time(tm_year=2024, tm_mon=3, tm_mday=15, tm_hour=15, tm_min=10, tm_sec=5, tm_wday=4, tm_yday=75, tm_isdst=0)

Key functions in the time module include:

FunctionDescription
time.sleep(secs)Pause execution for the specified number of seconds.
time.strftime(format[, t])Format a struct_time (or current local time if t is omitted) into a string based on format codes.
time.strptime(string, format)Parse a string representing a time according to a format into a struct_time.
time.mktime(t)Convert a local struct_time into seconds since the epoch (timestamp).
time.asctime([t])Convert a struct_time (or current local time) to a standard 24-character string format (e.g., ‘Fri Mar 15 11:10:05 2024’). Less flexible than strftime.
time.ctime([secs])Convert a timestamp (or current time) to a standard 24-character string format. Equivalent to asctime(localtime(secs)).
time.perf_counter()Return a high-resolution performance counter value (for measuring short durations).
time.process_time()Return the sum of system and user CPU time of the current process.

Note: time.clock() was deprecated in Python 3.3 and removed in Python 3.8. Use time.perf_counter() or time.process_time() instead for performance measurement.

The calendar module provides functions related to calendars, such as generating text calendars for months or years.

#!/usr/bin/env python3
import calendar
# Get the calendar for March 2024 as a string
cal_text = calendar.month(2024, 3)
print("Calendar for March 2024:")
print(cal_text)
# Check if a year is a leap year
is_leap = calendar.isleap(2024)
print(f"Is 2024 a leap year? {is_leap}")
# Get the weekday (0=Monday) for a specific date
weekday_code = calendar.weekday(2024, 3, 15)
print(f"Weekday for March 15, 2024 (0=Mon): {weekday_code}") # Output: 4 (Friday)

Output:

Calendar for March 2024:
March 2024
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
Is 2024 a leap year? True
Weekday for March 15, 2024 (0=Mon): 4

The calendar module also provides functions like calendar.calendar(year) for the full year, calendar.monthrange(year, month) to get the first weekday and number of days in a month, and calendar.setfirstweekday() to change the starting day of the week.

  • Logging: Timestamping events.
  • Scheduling Tasks: Running code at specific times or intervals.
  • Data Analysis: Analyzing time-series data.
  • Web Development: Handling session expiry, setting cookie lifetimes, displaying timestamps.
  • Calculating Durations: Finding the time difference between events.
  • User Interfaces: Displaying dates and times in user-friendly formats.