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.
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.
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.
import time
print(time.time())
1725533465.470414
Use the localtime() function to obtain a time tuple of the current local time.
import time
print(time.localtime(time.time()))
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)
• 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
Use the asctime() function to get a human-readable format of the time tuple.
import time
print(time.asctime(time.localtime(time.time())))
Thu Sep 05 15:31:39 2024
The sleep() method pauses execution for a specified number of seconds.
import time
for i in range(5):
print(i)
time.sleep(1)
0
1
2
3
4
Import the datetime module to create and manipulate date and time objects.
import datetime
print(datetime.datetime.now())
2024-09-05 10:54:38.014658
You can create date and datetime objects by specifying the year, month, day, and optionally time components.
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))
2020-04-04 00:00:00
2020-04-04 01:26:40
The calendar module provides functions to work with calendars.
import calendar
# Print the calendar for a specific month
print(calendar.month(2024, 9))
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
import calendar
print(calendar.prcal(2024))