Python Date

Python provides the datetime module to work with real dates and times. This module enables us to handle scheduling, timestamping, and various time-based operations in our scripts.

Key Classes in the datetime Module

The datetime module includes several classes:

1. date: Represents a date (year, month, day).

2. time: Represents a time (hour, minute, second, microsecond).

3. datetime: Combines both date and time.

4. timedelta: Represents the difference between two dates or times.

5. tzinfo: Provides time zone information.

6. timezone: Implements tzinfo for fixed offsets from UTC.

Time Ticks

In Python, time is measured in seconds since January 1, 1970, 00:00:00 UTC. This is known as the Unix epoch. The time() function from the time module returns the current time in ticks.

Example:

import time
print(time.time())

Output:

1725533465.470414

Getting the Current Time

Use the localtime() function to obtain a time tuple of the current local time.

Example:

import time
print(time.localtime(time.time()))

Output:

time.struct_time(tm_year=2024, tm_mon=9, tm_mday=5, tm_hour=10, tm_min=51, tm_sec=44, tm_wday=3, tm_yday=249, tm_isdst=0)

Time Tuple Attributes:

Year: 4 digits (e.g., 2018)

Month: 1 to 12

Day: 1 to 31

Hour: 0 to 23

Minute: 0 to 59

Second: 0 to 60

Day of Week: 0 (Monday) to 6 (Sunday)

Day of Year: 1 to 366

Daylight Savings: -1, 0, 1

Formatting Time

Use the asctime() function to get a human-readable format of the time tuple.

Example:

import time
print(time.asctime(time.localtime(time.time())))

Output:

Thu Sep 05 15:31:39 2024

Sleep Time

The sleep() method pauses execution for a specified number of seconds.

Example:

import time
for i in range(5):
    print(i)
    time.sleep(1)

Output:

0
1
2
3
4

Working with the datetime Module

Import the datetime module to create and manipulate date and time objects.

Example:

import datetime
print(datetime.datetime.now())

Output:

2024-09-05 10:54:38.014658

Creating Date Objects

You can create date and datetime objects by specifying the year, month, day, and optionally time components.

Examples:

import datetime

# Create a date object
print(datetime.datetime(2020, 4, 4))
# Create a datetime object with time
print(datetime.datetime(2020, 4, 4, 1, 26, 40))

Output:

2020-04-04 00:00:00
2020-04-04 01:26:40

The calendar Module

The calendar module provides functions to work with calendars.

Example:

import calendar
# Print the calendar for a specific month
print(calendar.month(2024, 9))

output:

September 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

Print the calendar for an entire year:

import calendar
print(calendar.prcal(2024))