Date Time Functions in Python

 


In Python, the datetime module provides classes for manipulating dates and times. It supports various functions to handle dates, times, and intervals, making it an essential tool for working with time-related tasks in Python.

Importing the datetime Module:

To work with dates and times in Python, you need to first import the datetime module.

  • import datetime


Basic Classes in datetime Module:

The datetime module has several key classes:

  • datetime: Combines date and time in a single object.

  • date: Represents just a date (year, month, and day).

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

  • timedelta: Represents the difference between two datetime objects.

  • tzinfo: Represents time zone information (used with datetime objects for time zone awareness).

Common Date and Time Functions

1. Current Date and Time

To get the current date and time, use the datetime.now() function.

  • import datetime


  • current_datetime = datetime.datetime.now()

  • print(current_datetime)  # Output: current date and time (e.g., 2025-02-17 12:34:56.789012)


2. Current Date

If you need only the current date, use the date.today() method.

  • import datetime


  • current_date = datetime.date.today()

  • print(current_date)  # Output: current date (e.g., 2025-02-17)


3. Current Time

To get the current time, use the datetime.now() and access the .time() method.

  • import datetime


  • current_time = datetime.datetime.now().time()

  • print(current_time)  # Output: current time (e.g., 12:34:56.789012)


4. Creating Specific Date and Time

You can create a datetime, date, or time object by passing specific values to the constructor.

  • # Creating a specific date

  • specific_date = datetime.date(2023, 5, 17)

  • print(specific_date)  # Output: 2023-05-17


  • # Creating a specific time

  • specific_time = datetime.time(14, 30, 0)

  • print(specific_time)  # Output: 14:30:00


  • # Creating a specific datetime

  • specific_datetime = datetime.datetime(2023, 5, 17, 14, 30, 0)

  • print(specific_datetime)  # Output: 2023-05-17 14:30:00


5. Formatting Dates and Times

You can format datetime objects into readable strings using the .strftime() method. It allows you to specify how the date and time should appear.

  • import datetime


  • current_datetime = datetime.datetime.now()


  • formatted_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

  • print(formatted_date)  # Output: 2025-02-17 12:34:56


  • # Format examples:

  • # %Y - Year (4 digits)

  • # %m - Month (2 digits)

  • # %d - Day (2 digits)

  • # %H - Hour (24-hour format)

  • # %M - Minute

  • # %S - Second


6. Parsing String into Date/Time

You can convert a string into a datetime object using the .strptime() method. This is helpful when you have a date or time in a specific format.

  • import datetime


  • date_string = "2025-02-17 12:34:56"

  • parsed_datetime = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

  • print(parsed_datetime)  # Output: 2025-02-17 12:34:56


7. Time Delta (Difference between Dates)

To calculate the difference between two datetime objects, you can use the timedelta class. This allows you to add or subtract time from a given datetime.

  • import datetime


  • # Create two datetime objects

  • datetime1 = datetime.datetime(2025, 2, 17, 12, 0, 0)

  • datetime2 = datetime.datetime(2025, 2, 18, 12, 0, 0)


  • # Calculate the difference

  • difference = datetime2 - datetime1

  • print(difference)  # Output: 1 day, 0:00:00 (timedelta object)


  • # Accessing days, seconds, and microseconds from timedelta

  • print(difference.days)  # Output: 1

  • print(difference.seconds)  # Output: 0


8. Adding/Subtracting Time

You can add or subtract time using the timedelta object. This allows you to perform operations like adding days, hours, minutes, etc., to a datetime object.

  • import datetime


  • current_datetime = datetime.datetime.now()


  • # Adding 5 days

  • new_datetime = current_datetime + datetime.timedelta(days=5)

  • print(new_datetime)


  • # Subtracting 2 hours

  • new_datetime = current_datetime - datetime.timedelta(hours=2)

  • print(new_datetime)


9. Getting Day of the Week

You can retrieve the weekday from a date or datetime object using .weekday(). It returns an integer (0 for Monday to 6 for Sunday).

  • import datetime


  • current_date = datetime.date.today()

  • weekday = current_date.weekday()

  • print(weekday)  # Output: 0 for Monday, 1 for Tuesday, ..., 6 for Sunday


Alternatively, you can use .strftime("%A") to get the full weekday name:

  • import datetime


  • current_date = datetime.date.today()

  • weekday_name = current_date.strftime("%A")

  • print(weekday_name)  # Output: Monday (or the corresponding day)


10. Time Zones (Timezone-Aware Dates)

Python's datetime module can handle time zones. You can make a datetime object timezone-aware using the pytz library (which you may need to install first).

  • import datetime

  • import pytz


  • # Get the current time in a specific timezone (e.g., New York)

  • timezone = pytz.timezone("America/New_York")

  • current_time = datetime.datetime.now(timezone)

  • print(current_time)  # Output: current time in New York timezone


Commonly Used Functions in datetime

  • datetime.datetime.now(): Returns the current local date and time.

  • datetime.datetime.today(): Similar to now(), but always in the local timezone.

  • datetime.datetime.utcnow(): Returns the current UTC date and time.

  • datetime.date.today(): Returns the current local date (without time).

  • datetime.datetime.strptime(): Converts a string into a datetime object.

  • datetime.datetime.strftime(): Formats a datetime object as a string.

Conclusion:

The datetime module in Python provides powerful tools for working with dates, times, and time intervals. You can perform operations like getting the current time, formatting date-time objects, adding/subtracting time, and calculating differences between dates.

If you need more examples or specific use cases, feel free to ask! 😊


Post a Comment

0 Comments