Python has a built-in module called datetime
which provides classes for working with dates and times. Here’s an overview of some of the main classes and functions in this module:
datetime.date
: Represents a date (year, month, day)datetime.time
: Represents a time of day (hour, minute, second, microsecond)datetime.datetime
: Represents a date and time (combination of date and time)datetime.timedelta
: Represents a duration (difference between two dates or times)
To use these classes, you need to import the datetime
module. Here’s an example of how to create a datetime
object:
import datetime dt = datetime.datetime(2023, 3, 12, 9, 30, 0) print(dt)
This will output: 2023-03-12 09:30:00
You can also get the current date and time using the datetime.now()
function:
import datetime now = datetime.datetime.now() print(now)
This will output the current date and time in your local timezone.
The datetime
module also provides various methods for working with dates and times, such as strftime()
for formatting dates and times as strings, and timedelta()
for performing arithmetic operations on dates and times.
Here’s an example of how to format a date and time as a string:
import datetime dt = datetime.datetime(2023, 3, 12, 9, 30, 0) formatted = dt.strftime('%Y-%m-%d %H:%M:%S') print(formatted)
This will output: 2023-03-12 09:30:00
And here’s an example of how to add a duration (in this case, 1 day) to a date:
import datetime d = datetime.date(2023, 3, 12) delta = datetime.timedelta(days=1) new_d = d + delta print(new_d)
This will output: 2023-03-13
Time tuple:
A time tuple is a tuple of 9 integers that represents a specific time. The 9 integers in a time tuple are:
(struct_time.tm_year, struct_time.tm_mon, struct_time.tm_mday, struct_time.tm_hour, struct_time.tm_min, struct_time.tm_sec, struct_time.tm_wday, struct_time.tm_yday, struct_time.tm_isdst)
Here’s what each of these integers represents:
tm_year
: The year, as a four-digit number (e.g. 2023)tm_mon
: The month, as a number between 1 (January) and 12 (December)tm_mday
: The day of the month, as a number between 1 and 31tm_hour
: The hour, as a number between 0 and 23tm_min
: The minute, as a number between 0 and 59tm_sec
: The second, as a number between 0 and 61 (to account for leap seconds)tm_wday
: The day of the week, as a number between 0 (Monday) and 6 (Sunday)tm_yday
: The day of the year, as a number between 1 and 366tm_isdst
: A flag that indicates whether daylight saving time is in effect (1 if it is, 0 if it is not, and -1 if it is unknown)
You can get a time tuple using the time.localtime()
function, which returns the current local time as a time tuple. Here’s an example:
import time t = time.localtime() print(t)
This will output something like:
time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=10, tm_min=30, tm_sec=0, tm_wday=6, tm_yday=71, tm_isdst=0)
You can also create a time tuple manually using the time.struct_time()
function. For example:
import time t = time.struct_time((2023, 3, 12, 10, 30, 0, 0, 0, 0)) print(t)
This will output:
time.struct_time(tm_year=2023, tm_mon=3, tm_mday=12, tm_hour=10, tm_min=30, tm_sec=0, tm_wday=6, tm_yday=71, tm_isdst=0)
Getting formatted time:
To get a formatted time string, you can use the time.strftime()
function. This function takes a format string as its first argument and returns a string representing the current time formatted according to that format string.
The format string consists of various format codes, which are replaced by the corresponding values when the string is formatted. Here are some of the most common format codes:
%Y
: Year with century as a decimal number%m
: Month as a decimal number (01 – 12)%d
: Day of the month as a decimal number (01 – 31)%H
: Hour (24-hour clock) as a decimal number (00 – 23)%M
: Minute as a decimal number (00 – 59)%S
: Second as a decimal number (00 – 59)%a
: Abbreviated weekday name (Sun, Mon, Tue, etc.)%A
: Full weekday name (Sunday, Monday, Tuesday, etc.)%b
: Abbreviated month name (Jan, Feb, Mar, etc.)%B
: Full month name (January, February, March, etc.)%p
: Locale’s equivalent of AM or PM (if any)
Here’s an example of how to use time.strftime()
to get the current time in a formatted string:
import time formatted_time = time.strftime('%Y-%m-%d %H:%M:%S') print(formatted_time)
This will output a string like 2023-03-12 11:30:00
, which represents the current date and time in the format specified by the format string.
You can also pass a struct_time
tuple as the second argument to time.strftime()
to format a specific time. For example:
import time t = time.struct_time((2023, 3, 12, 10, 30, 0, 0, 0, 0)) formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', t) print(formatted_time)
This will output a string like 2023-03-12 10:30:00
, which represents the time specified by the struct_time
tuple in the format specified by the format string.
Python sleep time:
In Python, you can pause the execution of a program for a specified amount of time using the time.sleep()
function. This function takes a single argument, which is the number of seconds to pause the program.
Here’s an example of how to use time.sleep()
to pause the program for 5 seconds:
import time print('Starting...') time.sleep(5) print('Done!')
When you run this program, it will print “Starting…”, pause for 5 seconds, and then print “Done!”.
You can also use fractions of a second as the argument to time.sleep()
. For example, to pause the program for 250 milliseconds (i.e. a quarter of a second), you can use time.sleep(0.25)
.
Note that while the program is paused, the CPU is idle and not doing any work. This means that if you need to perform some other task while the program is paused (such as responding to user input), you should use a different mechanism such as threading or asynchronous programming.
The datetime Module:
The datetime
module in Python provides classes for working with dates and times. It includes several classes, such as date
, time
, datetime
, and timedelta
, which allow you to perform various operations with dates and times.
Here are some of the most commonly used classes and methods in the datetime
module:
datetime.date
: Represents a date (year, month, and day) and provides methods for working with dates, such asweekday()
to get the day of the week,strftime()
to format the date as a string, andtoday()
to get the current date.datetime.time
: Represents a time (hour, minute, second, microsecond) and provides methods for working with times, such asstrftime()
to format the time as a string.datetime.datetime
: Represents both a date and a time and provides methods for working with both, such asstrftime()
to format the date and time as a string, andnow()
to get the current date and time.datetime.timedelta
: Represents a duration of time and provides methods for performing arithmetic with durations, such as adding or subtracting durations from dates or times.
Here’s an example of how to use the datetime
module to work with dates and times:
import datetime # Get the current date and time now = datetime.datetime.now() print("Current date and time:", now) # Get the current date today = datetime.date.today() print("Today's date:", today) # Create a date object d = datetime.date(2023, 3, 12) print("Date:", d) # Create a time object t = datetime.time(11, 30, 0) print("Time:", t) # Create a datetime object dt = datetime.datetime(2023, 3, 12, 11, 30, 0) print("Datetime:", dt) # Format a datetime object as a string s = dt.strftime("%Y-%m-%d %H:%M:%S") print("Formatted datetime:", s) # Create a timedelta object delta = datetime.timedelta(days=1) print("Timedelta:", delta) # Add a timedelta to a date new_date = d + delta print("New date:", new_date)
This will output:
Current date and time: 2023-03-12 11:30:00.000000 Today's date: 2023-03-12 Date: 2023-03-12 Time: 11:30:00 Datetime: 2023-03-12 11:30:00 Formatted datetime: 2023-03-12 11:30:00 Timedelta: 1 day, 0:00:00 New date: 2023-03-13
Creating date objects:
In Python, you can create a date
object using the date
class from the datetime
module. The date
class requires three arguments: the year, the month, and the day.
Here’s an example of how to create a date
object:
import datetime d = datetime.date(2023, 3, 12) print(d)
When you run this code, it will output:
2023-03-12
This creates a date
object representing March 12th, 2023.
You can also create a date
object representing the current date using the today()
method:
import datetime today = datetime.date.today() print(today)
This will output the current date in the format YYYY-MM-DD
, such as 2023-03-12
.
Once you have a date
object, you can access its year, month, and day using the year
, month
, and day
attributes, respectively:
import datetime d = datetime.date(2023, 3, 12) print(d.year) print(d.month) print(d.day)
This will output:
2023 3 12
You can also get the day of the week as an integer using the weekday()
method, where Monday is 0 and Sunday is 6:
import datetime d = datetime.date(2023, 3, 12) print(d.weekday()) # 6 (Sunday)
Comparison of two dates:
In Python, you can compare two date
objects using comparison operators such as <
, <=
, >
, and >=
. The comparison is based on the chronological order of the dates.
Here’s an example of how to compare two date
objects:
import datetime d1 = datetime.date(2023, 3, 12) d2 = datetime.date(2023, 3, 15) if d1 < d2: print("d1 is before d2") elif d1 == d2: print("d1 is the same as d2") else: print("d1 is after d2")
This will output:
d1 is before d2
In this example, d1
represents March 12th, 2023, and d2
represents March 15th, 2023. The code compares the two dates using the <
operator and prints a message indicating which date comes first in chronological order.
You can also compare a date
object with the current date using the today()
method:
import datetime d = datetime.date(2023, 3, 12) today = datetime.date.today() if d < today: print("d is in the past") elif d == today: print("d is today!") else: print("d is in the future")
This will output:
d is in the past
In this example, the code compares the date
object d
with the current date using the <
operator and prints a message indicating whether d
is in the past, today, or in the future.
The calendar module:
The calendar
module in Python provides various functions related to calendars. This module allows you to output calendars like the traditional Unix cal
program and provides additional useful functions related to calendars.
Here are some examples of how to use the calendar
module:
1. Printing a calendar for a specific month and year
To print a calendar for a specific month and year, you can use the month
function, which takes two arguments: the year and the month.
import calendar calendar.month(2023, 3)
This will output the following calendar for March 2023:
March 2023 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
2. Printing a calendar for an entire year
To print a calendar for an entire year, you can use the calendar
function, which takes one argument: the year.
import calendar calendar.calendar(2023)
This will output the following calendar for the year 2023:
2023 January February March Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 1 2 3 4 5 1 2 3 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24 23 24 25 26 27 28 29 27 28 25 26 27 28 29 30 31 30 31 April May June Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 1 1 2 3 4 5 6 3 4 5 6 7 8 9 2 3 4 5 6 7 8 7 8 9 10 11 12 13 10 11 12 13 14 15 16 9 10 11 12 13 14 15 14 15 16 17 18 19 20 17 18 19 20 21 22 23 16 17 18 19 20 21 22 21 22 23 24 25 26 27 24 25 26 27 28 29 30 23 24 25 26 27 28 29