Python - Time & Calendar Module

The time module in Python provides functionality to work with time-related tasks such as getting the current time, measuring the time taken by a code block to execute, etc. Here are some examples of using the time module:

Getting the Current Time

You can use the time() function to get the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC).

import time
current_time = time.time()
print(current_time)
#Output: 1649011667.1538355

Converting Seconds to a Struct Time Object

The gmtime() function converts the given number of seconds since the Epoch to a struct time object that represents the time in the UTC timezone.

import time
seconds_since_epoch = 1649011667.1538355
struct_time = time.gmtime(seconds_since_epoch)
print(struct_time)
#Output: time.struct_time(tm_year=2023, tm_mon=4, tm_mday=2, tm_hour=17, tm_min=1, tm_sec=7, tm_wday=5, tm_yday=92, tm_isdst=0)

Formatting Time

You can use the strftime() function to format a struct time object as a string.

import time
struct_time = (2022, 4, 2, 17, 1, 7, 5, 92, 0)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(formatted_time)
#Output: 2022-04-02 17:01:07

Measuring the Execution Time of Code

You can use the perf_counter() function to measure the execution time of a code block.

import time
start_time = time.perf_counter()
# code block to measure
for i in range(1000000):
    pass
end_time = time.perf_counter()
print("Execution Time:", end_time - start_time, "seconds")
#Output: Execution Time: 0.02050419999999996 seconds

The calendar module in Python provides useful functions to work with calendars, including the Gregorian calendar used in most of the world. It provides functions to display calendars for any month and year, determine the day of the week for a given date, and calculate the number of days between two dates.

Here are some examples of how to use the calendar module:

Displaying a calendar for a given month and year:

import calendar
# Display calendar for March 2023
print(calendar.month(2023, 3))

Determining the day of the week for a given date:

import calendar
# Determine the day of the week for June 1, 2022
day = calendar.weekday(2022, 6, 1)
# Print the day of the week (0=Monday, 6=Sunday)
print(day)
#Output: 2

In this example, weekday() returns 2, which represents Wednesday.

Calculating the number of days between two dates:

import calendar
# Calculate the number of days between May 1, 2022 and June 1, 2022
days = calendar.monthrange(2022, 5)[1] - 1 + (calendar.monthrange(2022, 6)[0] + 1) + 30
# Print the number of days
print(days)
#Output: 31

In this example, monthrange() returns a tuple containing the first weekday of the month (0=Monday) and the number of days in the month. We use this information to calculate the number of days between May 1 and June 1, 2022, which is 31.