0% found this document useful (0 votes)
6 views4 pages

13 BSC CS - Python - Chapter 6

The document provides an overview of working with date and time in Python using the datetime and time modules. It covers common functions for retrieving and formatting dates and times, as well as comparing and sorting them. Additionally, it introduces the calendar module for displaying calendar views and checking leap years.

Uploaded by

HARSH MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

13 BSC CS - Python - Chapter 6

The document provides an overview of working with date and time in Python using the datetime and time modules. It covers common functions for retrieving and formatting dates and times, as well as comparing and sorting them. Additionally, it introduces the calendar module for displaying calendar views and checking leap years.

Uploaded by

HARSH MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

13 B.Sc. CS Sem - I ​ ​ 6.

Date and Time

from datetime import date


Working with Time

The time module in Python allows you to work Common Functions:


with time-related functions.
○​ date.today(): Returns the current local
Using this module, you can retrieve the current date.
time, measure time intervals, and perform ○​ date(year, month, day): Creates a date
time-related calculations. object with specified year, month, and day.

Syntax: Example Code:

E
import time from datetime import date​

EG
# Get today's date​
Common Functions: today = date.today()​
print("Today's date:", today)​

LL
○​ time.time(): Returns the current time in ​
seconds since the Unix epoch (January 1, # Creating a specific date​
1970).

O
○​ time.ctime(): Converts a time in seconds specific_date = date(2023, 10,
3)​

C
to a readable format.
○​ time.sleep(seconds): Pauses the execution print("Specific date:",
for a specified number of seconds.
EE
specific_date)

Example Code:
Working with Date and Time Now
R

import time​
EG

To retrieve both date and time in Python, use


# Get current time in seconds the datetime class from the datetime module.
since epoch​
This lets you obtain the current date and time
.D

current_time = time.time()​
accurately, down to the microsecond.
print("Current time in seconds
since epoch:", current_time)​ Syntax:
.M

# Convert to readable format​


readable_time =
.P

from datetime import datetime


time.ctime(current_time)​
IG

print("Readable current time:",


Common Functions:
readable_time)​
# Sleep for 2 seconds​ ○​ datetime.now(): Returns the current date
R

print("Pausing for 2 and time.


SH

seconds...")​ ○​ datetime(year, month, day, hour,


time.sleep(2)​ minute, second): Creates a specific date
and time object.
print("Resumed after sleep.")
Example Code:
Working with Date
from datetime import datetime​
Python's datetime module enables handling
# Get current date and time​
dates in a more human-readable way,
supporting year, month, and day retrieval and current_datetime =
formatting. datetime.now()​
print("Current date and time:",
Syntax: current_datetime)​

1
# Creating a specific date and ○​ %Y: Year with century (e.g., 2023)
○​ %m: Month as a zero-padded decimal (e.g.,
time​
01)
specific_datetime = ○​ %d: Day of the month as a zero-padded
datetime(2023, 10, 3, 14, 30, 0)​ decimal (e.g., 09)
print("Specific date and time:", ○​ %H: Hour (24-hour clock) as a zero-padded
specific_datetime) decimal (e.g., 14)
○​ %M: Minute as a zero-padded decimal
(e.g., 30)
○​ %S: Second as a zero-padded decimal (e.g.,
00)
Combining Date and Time
Example Code:
To combine dates and times in Python, the

E
datetime module provides functionality to
create a datetime object by merging a date and from datetime import datetime​

EG
a time object, or by specifying all components now = datetime.now()​
directly. formatted_date =
now.strftime("%Y-%m-%d

LL
Syntax: %H:%M:%S")​
print("Formatted date and

O
from datetime import datetime, time:", formatted_date)​
date, time

C
# Custom format example​
custom_format =
EE
Example Code: now.strftime("%A, %B %d, %Y -
%I:%M %p")​
from datetime import datetime, print("Custom formatted date and
R

date, time​ time:", custom_format)


EG

# Creating separate date and


time objects​ Finding and Comparing Dates
date_part = date(2023, 10, 3)​
.D

time_part = time(14, 30)​ You can find the difference between dates and
# Combining date and time​ compare them using simple comparison
operators.
.M

combined_datetime =
datetime.combine(date_part, The datetime module also supports timedelta
.P

time_part)​ for finding differences in dates and times.


print("Combined date and time:",
IG

combined_datetime) Syntax:
R

Formatting Date and Time from datetime import datetime,


timedelta
SH

Date and time formatting allows you to display


them in various styles. Common Comparisons:
The strftime() method formats a datetime ○​ date1 < date2: Checks if date1 is earlier
object as a string according to a specified than date2.
format code. ○​ date1 > date2: Checks if date1 is later
than date2.
Syntax:
○​ timedelta: Represents a duration, the
difference between two dates or times.
datetime_object.strftime(format_
code) Example Code:

Common Format Codes:


2
from datetime import datetime, sorted_dates = sorted(dates)​
timedelta​ print("Sorted dates:",
# Creating two datetime objects​ sorted_dates)
date1 = datetime(2023, 10, 3,
14, 30)​ Knowing the Time Taken by a Program
date2 = datetime(2023, 10, 5,
18, 45)​ Measuring program execution time is useful
# Finding the difference between for performance analysis.
dates​ The time module provides time.time() and
difference = date2 - date1​ time.perf_counter() to capture the start and end
print("Difference:", difference)​ times of a code block.
# Comparing dates​

E
if date1 < date2:​ Syntax:

EG
print("date1 is earlier than
date2")​ import time​
start_time = time.time()​

LL
else:​
print("date1 is later than # code to measure​
or equal to date2")​ end_time = time.time()

O
# Adding days to a date​

C
new_date = date1 +
timedelta(days=7)​
Example Code:
EE
print("Date after 7 days:",
new_date)
import time​
R

start_time = time.time()​
Sorting Dates
EG

# Code block to measure​


Python lists can store multiple datetime for _ in range(1000000):​
objects, which can then be sorted using the pass​
.D

sorted() function or list.sort() method. end_time = time.time()​


elapsed_time = end_time -
When sorting, Python orders dates from the
.M

start_time​
earliest to the latest by default.
print("Time taken by program:",
.P

Syntax: elapsed_time, "seconds")


IG

sorted_date_list = Working with the Calendar Module


sorted(list_of_dates)
The calendar module in Python allows you to
R

work with dates and retrieve formatted


SH

Example Code: calendar views.

from datetime import datetime​ This module provides functionality to display


# Creating a list of date months, years, check leap years, and find the
day of the week.
objects​
dates = [​ Syntax:
datetime(2023, 10, 5),​
datetime(2023, 9, 21),​ import calendar
datetime(2023, 12, 11),​
datetime(2023, 7, 19)​
Common Functions:
]​
# Sorting the dates​

3
○​ calendar.month(year, month): Returns a
multi-line string representation of the
specified month.
○​ calendar.isleap(year): Checks if the
specified year is a leap year.
○​ calendar.weekday(year, month, day):
Returns the weekday (0 for Monday to 6
for Sunday).

Example Code:

import calendar​
# Display a specific month​

E
print("October 2023 calendar:")​

EG
print(calendar.month(2023, 10))​
# Check if a year is a leap year​
year = 2024​

LL
print(f"Is {year} a leap year?",
calendar.isleap(year))​

O
# Find the day of the week for a
given date​

C
day_of_week =
calendar.weekday(2023, 10, 3)​
EE
print("The weekday for October
3, 2023 is:",
R

calendar.day_name[day_of_week])
EG
.D
.M
.P
IG
R
SH

You might also like