Introduction to the calendar and time Modules for Timestamps
Date and time handling is another important aspect, especially when dealing with file timestamps for backups, logging, or scheduling. Python provides several modules for this, but two basic ones are:
time – low-level time-related functions (timestamps, sleep, etc.).
calendar – functions for calendar dates, such as printing calendars and checking days.
We’ll touch on these to get a current timestamp and to work with calendar dates. (The datetime module is more powerful for date/time arithmetic, but here we focus on time and calendar as per our syllabus.)
Using the time Module
The time module is useful for working with timestamps (points in time) and simple time-related tasks.
Current Time (Timestamp): time.time() returns the current time as a timestamp, which is the number of seconds since the Unix epoch (Jan 1, 1970) in UTC. It returns a float (with sub-second precision). Example:
import time
now_ts = time.time()
print(now_ts)
Output will be a large number like 1754862050.4579918 (your output will vary). This is rarely human-readable, but is useful for calculations (e.g., measure durations) or storing an absolute time.
Convert Timestamp to Structured Time: time.localtime(timestamp) converts a timestamp to a struct_time (a tuple-like object) in local time. If you omit the timestamp, it uses the current time. For example:
current_struct = time.localtime()
print(current_struct.tm_year, current_struct.tm_mon, current_struct.tm_mday)
This might print something like 2025 8 6 for 6th August 2025. The struct_time has attributes like tm_year, tm_mon (month), tm_mday (day of month), tm_hour, tm_min, tm_sec, etc.
Formatted Date/Time Strings: To get a nicely formatted date/time string (timestamp in human-readable form), use time.strftime(format, [t]). The strftime function formats a time tuple (t) according to a format string. If you don’t provide t, it will format the current local time. Format strings use placeholders like %Y for year, %m for month, %d for day, %H for hour (24-hour clock), %M for minute, %S for second, etc.
Example – get the current date/time as a string:
import time
now_str = time.strftime("%Y-%m-%d %H:%M:%S")
print("Current date and time:", now_str)
This might output: Current date and time: 2025-08-06 23:20:45 (depending on when you run it). Here %Y became 2025, %m 08, %d 06, etc., constructing a familiar datetime format.
You can change the format string to many different combinations. For instance, %A for full weekday name, %B for full month name, %I for 12-hour clock hour, %p for AM/PM, and so on. time.strftime is very flexible for creating timestamp strings for filenames or logs.
Pausing Execution: Not directly related to timestamps, but worth knowing: time.sleep(seconds) will pause your script for the given number of seconds. For example, time.sleep(1.5) waits 1.5 seconds. This can be useful in scheduling loops or waiting for a certain time.
Using the calendar Module
The calendar module is handy for tasks related to dates and calendars. It can generate calendars and provide info about days.
Print a Calendar: You can print a text calendar for a month using calendar.month(year, month). This returns a string with a simple text calendar. For example:
import calendar
cal_str = calendar.month(2025, 8)
print(cal_str)
Output:
August 2025
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
This is a nicely formatted calendar for August 2025.
Similarly, calendar.calendar(year) will return a whole year’s calendar as a big string (12 months). There are also calendar.prmonth(year, month) and calendar.prcal(year) that directly print to stdout.
Weekday and Week Information: The function calendar.weekday(year, month, day) returns the day of the week as an integer, where Monday is 0 and Sunday is 6 by default. For example:
day_index = calendar.weekday(2025, 8, 6)
print(day_index) # 0=Mon, 1=Tue, ..., 6=Sun
For Aug 6, 2025, this will print 2 (if Monday=0, that means Wednesday, since 0->Mon,1->Tue,2->Wed). If you want the name of the day, you can use:
import calendar
days = list(calendar.day_name) # ['Monday', 'Tuesday', ... 'Sunday']
print(days[day_index]) # e.g., "Wednesday"
The calendar module provides calendar.day_name (an iterable of weekday names) and calendar.month_name for month names if needed.
Useful Calendar Functions:
-
calendar.isleap(year) returns True if the given year is a leap year, False otherwise.
-
calendar.leapdays(y1, y2) tells how many leap years are between year1 and year2 (exclusive of y2).
-
calendar.monthrange(year, month) returns a tuple (start_day, num_days) where start_day is the weekday index of the first day of that month and num_days is the number of days in the month.
These can be used for calculations or validations involving dates.
Using time and calendar together: Often you might get the current date/time with time and then use calendar for something. For instance, if you want to timestamp a backup file with the current date, you could do:
timestamp = time.strftime("%Y%m%d") # e.g., "20250806" for Aug 6, 2025
backup_filename = f"backup_{timestamp}.zip"
Here we used time.strftime to get a compact date stamp. We could also have used datetime module for this, but this works fine for simple cases.
Another example: schedule something only on weekends:
today = time.localtime()
weekday_idx = today.tm_wday # tm_wday: 0=Monday ... 6=Sunday
if weekday_idx >= 5: # 5=Saturday, 6=Sunday
print("It's the weekend, run maintenance tasks.")
(Note: tm_wday from time.localtime() uses Monday=0, Sunday=6 which aligns with calendar’s convention.)
The calendar module can produce outputs or compute values that might not be needed in every script, but it’s good to be aware of it. For our use, generating timestamps (with time) is likely more relevant, especially when naming backup files or logging times of operations.
