Python - Date & Time

In Python, we can work with dates and times using the built-in datetime module. The datetime module provides various classes and functions to represent and manipulate dates and times.

To work with dates, we can use the date class. To work with times, we can use the time class. And to work with both dates and times, we can use the datetime class.

Here's an example of how to create a datetime object representing the current date and time:

import datetime
now = datetime.datetime.now()
print("Current date and time:", now)
#This will output something like:
#Current date and time: 2023-04-01 09:47:23.918324

We can also create datetime objects representing specific dates and times using the datetime constructor:

import datetime
my_date = datetime.datetime(2022, 12, 25, 12, 0, 0)
print("My date:", my_date)
#This will output:
#My date: 2022-12-25 12:00:00

We can perform various operations on datetime objects, such as adding or subtracting time intervals, formatting the date and time as strings, and comparing two datetime objects. Here are some examples:

import datetime
now = datetime.datetime.now()
one_hour_later = now + datetime.timedelta(hours=1)
print("One hour later:", one_hour_later)
one_week_ago = now - datetime.timedelta(weeks=1)
print("One week ago:", one_week_ago)
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
date_string = "2022-12-25 12:00:00"
my_date = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("My date:", my_date)
if now < one_hour_later:
    print("One hour later is in the future")
else:
    print("One hour later is in the past")