Python 3 - Date & Time
Python 3 - Date & Time
Section titled “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.
Understanding Timestamps (Epoch Time)
Section titled “Understanding Timestamps (Epoch Time)”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’.
Example: Getting the Current Timestamp
Section titled “Example: Getting the Current 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.123456While 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 thezoneinfomodule 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 timenow = datetime.datetime.now()print(f"Current date and time: {now}")
# Get the current date onlytoday = datetime.date.today()print(f"Current date: {today}")
# Create a specific datespecific_date = datetime.date(2024, 3, 15)print(f"Specific date: {specific_date}")Output:
Current date and time: 2024-03-15 10:30:00.123456Current date: 2024-03-15Specific date: 2024-03-15Formatting Dates and Times
Section titled “Formatting Dates and Times”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.
Example: Using strftime()
Section titled “Example: Using strftime()”#!/usr/bin/env python3
import datetime
now = datetime.datetime.now()
# Format examplesprint(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 formatOutput (example):
Standard format: 2024-03-15 10:45:12.123456MM/DD/YY: 03/15/24Full month name, day, year: March 15, 2024Time (HH:MM:SS): 10:45:12Date and Time (ISO 8601): 2024-03-15T10:45:12.123456You can find a complete list of formatting codes in the Python documentation: strftime() and strptime() Format Codes.
Time Zones
Section titled “Time Zones”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.
Example: Using zoneinfo (Python 3.9+)
Section titled “Example: Using zoneinfo (Python 3.9+)”#!/usr/bin/env python3
import datetime# zoneinfo requires Python 3.9+ and the tzdata package on some systems# pip install tzdatafrom zoneinfo import ZoneInfo
# Get current time in UTCutc_now = datetime.datetime.now(datetime.timezone.utc)print(f"UTC Time: {utc_now}")
# Convert to a specific time zoneny_tz = ZoneInfo("America/New_York")ny_now = utc_now.astimezone(ny_tz)print(f"New York Time: {ny_now}")
# Create a timezone-aware datetime directlylondon_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:00New York Time: 2024-03-15 11:05:30.123456-04:00London Time: 2024-03-15 12:00:00+00:00Note: 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.
What is struct_time?
Section titled “What is 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:
| Index | Attribute | Field | Values |
|---|---|---|---|
| 0 | tm_year | Year | e.g., 2024 |
| 1 | tm_mon | Month | 1 to 12 |
| 2 | tm_mday | Day | 1 to 31 |
| 3 | tm_hour | Hour | 0 to 23 |
| 4 | tm_min | Minute | 0 to 59 |
| 5 | tm_sec | Second | 0 to 61 (60/61 for leap seconds) |
| 6 | tm_wday | Day of Week | 0 to 6 (Monday is 0) |
| 7 | tm_yday | Day of Year | 1 to 366 |
| 8 | tm_isdst | Daylight Savings | 0 (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 timestampcurrent_timestamp = time.time()
# Convert timestamp to local struct_timelocal_time_struct = time.localtime(current_timestamp)print(f"Local time (struct_time): {local_time_struct}")
# Access specific fieldsprint(f"Year: {local_time_struct.tm_year}")print(f"Hour: {local_time_struct.tm_hour}")
# Convert timestamp to UTC struct_timegmt_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: 2024Hour: 11UTC 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)Other Useful time Functions
Section titled “Other Useful time Functions”Key functions in the time module include:
| Function | Description |
|---|---|
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
Section titled “The calendar Module”The calendar module provides functions related to calendars, such as generating text calendars for months or years.
Example: Printing a Month’s Calendar
Section titled “Example: Printing a Month’s Calendar”#!/usr/bin/env python3
import calendar
# Get the calendar for March 2024 as a stringcal_text = calendar.month(2024, 3)
print("Calendar for March 2024:")print(cal_text)
# Check if a year is a leap yearis_leap = calendar.isleap(2024)print(f"Is 2024 a leap year? {is_leap}")
# Get the weekday (0=Monday) for a specific dateweekday_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 2024Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
Is 2024 a leap year? TrueWeekday for March 15, 2024 (0=Mon): 4The 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.
Practical Applications
Section titled “Practical Applications”- 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.
Further Resources
Section titled “Further Resources”- Python
datetimemodule documentation: https://docs.python.org/3/library/datetime.html - Python
timemodule documentation: https://docs.python.org/3/library/time.html - Python
calendarmodule documentation: https://docs.python.org/3/library/calendar.html - Python
zoneinfomodule documentation: https://docs.python.org/3/library/zoneinfo.html - Dateutil library (third-party, powerful extensions): https://dateutil.readthedocs.io/