Python From Beginner to Advanced

0% completed

Previous
Next
Python - Date & Time

Handling date and time is a fundamental requirement in many programming tasks, from logging and timestamping in applications to scheduling and automation features. Python provides a comprehensive set of built-in modules for managing date and time data, primarily through the datetime, time, and calendar modules. This lesson will explore these modules, providing a detailed look at their capabilities and usage with practical examples.

Python's datetime Module

The datetime module in Python offers classes for manipulating dates and times in both simple and complex ways. It not only supports the manipulation of dates, times, and intervals but also their formatting and parsing.

Key Classes in datetime Module

  • datetime.date: For manipulating just dates (year, month, day).
  • datetime.time: For time independent of any particular day.
  • datetime.datetime: Combines a date and a time (year, month, day, hour, minute, second, microsecond).
  • datetime.timedelta: For representing differences in time, allows addition and subtraction of dates.

Example 1: Working with datetime.date

This example demonstrates how to create and manipulate dates using datetime.date.

Python3
Python3

. . . .

Explanation:

  • datetime.date(2022, 12, 25): Creates a date object for December 25, 2022.
  • datetime.date.today(): Returns the current local date.
  • Accessing year, month, and day attributes to get respective date parts.

Example 2: Using datetime.timedelta

This example shows how to calculate new dates using time deltas.

Python3
Python3

. . . .

Explanation:

  • datetime.timedelta(weeks=1): Represents a time span of one week.
  • today + one_week: Computes a date one week from today.

Python's time Module

The time module provides access to various time-related functions. It is particularly useful for Unix timestamp manipulation and working with time in terms of seconds since the epoch (January 1, 1970, 00:00:00 UTC).

Key Functions in time Module

  • time.time(): Returns the current time as a floating-point number expressed in seconds since the epoch.
  • time.sleep(): Suspends the execution of the calling thread for the given number of seconds.

Example: Using time.time() and time.sleep()

Python3
Python3

. . . .

Explanation:

  • time.time(): Fetches the current time as a number of seconds since the epoch.
  • time.sleep(5): Pauses the script for 5 seconds.

Advanced Date and Time Handling

After covering the basics of datetime and time modules, we will now explore more advanced topics including formatting, parsing, and working with the calendar module.

Python’s datetime module allows for easy formatting of dates and times into human-readable strings and vice versa, using the strftime() and strptime() methods.

Example: Formatting Dates and Times

Python3
Python3

. . . .

Explanation:

  • strftime("%Y-%m-%d %H:%M:%S"): Converts a datetime object into a string formatted according to the specified format codes, where %Y is the full year, %m is the month, %d is the day, %H for hours, %M for minutes, and %S for seconds.

Example: Parsing Strings into Dates

Python3
Python3

. . . .

Explanation:

  • strptime(date_string, "%Y-%m-%d %H:%M:%S"): Parses a string representing a date and time into a datetime object, using the same format codes.

Working with the Calendar Module

The calendar module in Python is used for displaying calendars and managing related data. It supports operations such as fetching the month or year calendar in text or HTML form.

Example: Using calendar to Print a Month's Calendar

Python3
Python3

. . . .

Explanation:

  • calendar.month(2022, 12): Generates a string representing a monthly calendar for December 2022.

Handling Leap Years with calendar

Python3
Python3

. . . .

Explanation:

  • calendar.isleap(year): Returns True if the specified year is a leap year, otherwise False.

This comprehensive lesson has covered handling dates and times in Python, from basic date creation and manipulation to more advanced formatting, parsing, calendar functions, and timezone handling. By understanding these concepts, Python developers can effectively manage date and time data in their applications, ensuring they handle scheduling, logging, and time conversion tasks accurately.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next