How to Manipulate Dates and Times in Python with Datetime

Welcome to the fascinating world of date and time manipulation in Python! When it comes to handling dates and times, Python has got you covered with its built-in DateTime module. No need for external installations, as this powerful module is readily available for you to explore.

In this blog, we’ll show you how to use the Python datetime module to work with dates and times. We’ll cover everything from creating date and time objects to formatting.

So, whether you’re a beginner or an experienced one, get ready to unlock the full potential of Python’s DateTime module and embark on a thrilling journey of temporal exploration. Let’s dive in and master the art of manipulating dates and times in Python like a pro.

Python DateTime module

The Python DateTime module is a useful tool that helps you work with dates and times in Python. It comes built-in with Python, so you don’t need to install anything extra. This module allows you to perform various tasks like creating, changing, formatting, and calculating with dates and times.

You can use it to handle different time zones, calculate time differences, or display dates in a specific format. With Python DateTime, you have all the tools you need to make working with dates and times in your Python programs a breeze.

Python Date time module Syntax:

1. Creating a date object

import datetime
date_obj = datetime.date(year, month, day)

Example

import datetime

year = 2023
month = 7
day = 11

date_obj = datetime.date(year, month, day)

In this example, the datetime module is imported, allowing you to access its functions and classes. Then, a date object named date_obj is created using the datetime.date() function, passing the year, month, and day values as arguments. The year, month, and day variables can be replaced with the desired values based on your specific needs.

2. Create a time object

import datetime
time_obj = datetime.time(hour, minute, second, microsecond)

Example

import datetime

hour = 10
minute = 30
second = 0
microsecond = 500000

time_obj = datetime.time(hour, minute, second, microsecond)

In this example, the datetime module is imported, allowing you to access its functions and classes. Then, a time object named time_obj is created using the datetime.time() function, passing the hour, minute, second, and microsecond values as arguments. The hour, minute, second, and microsecond variables can be replaced with the desired values based on your specific needs.

3. Creating a datetime object

import datetime
datetime_obj = datetime.datetime(year, month, day, hour, minute, second, microsecond)

Example

import datetime

year = 2023
month = 7
day = 11
hour = 10
minute = 30
second = 0
microsecond = 500000

datetime_obj = datetime.datetime(year, month, day, hour, minute, second, microsecond)

In this example, the datetime module is imported, allowing you to access its functions and classes. Then, a datetime object named datetime_obj is created using the datetime.datetime() function, passing the year, month, day, hour, minute, second, and microsecond values as arguments.

The variables year, month, day, hour, minute, second, and microsecond can be replaced with the desired values based on your specific needs.

4. Getting the current date and time

import datetime
current_datetime = datetime.datetime.now()

In this example, the datetime module is imported, allowing you to access its functions and classes. By calling datetime.datetime.now(), you can retrieve the current date and time, which will be stored in the current_datetime variable. This provides you with the current date and time information at the moment the code is executed.

Formatting a date or time

formatted_date = date_obj.strftime("Format")
formatted_time = time_obj.strftime("Format")

Example

import datetime

# Assuming you have already created date_obj and time_obj

# Formatting the date object
formatted_date = date_obj.strftime("%Y-%m-%d")

# Formatting the time object
formatted_time = time_obj.strftime("%H:%M:%S")

In this example, the strftime() method is used to format the date_obj and time_obj objects. The format string “%Y-%m-%d” is used for the date object to represent the year, month, and day in a specific format. Similarly, the format string “%H:%M:%S” is used for the time object to represent the hour, minute, and second in a specific format.

You can adjust the format strings according to your desired date and time representation. The formatted date and time will be stored in the formatted_date and formatted_time variables, respectively.

6. Performing calculations with dates and times

time_difference = datetime_obj1 - datetime_obj2

Example

import datetime

# Assuming you have already created datetime_obj1 and datetime_obj2

# Calculating the time difference
time_difference = datetime_obj1 - datetime_obj2

In this example, the time_difference variable will store the result of subtracting datetime_obj2 from datetime_obj1, giving you the time duration between the two datetime objects.

The resulting time_difference will be a timedelta object, which represents the difference in days, seconds, and microseconds. You can then utilize this information for further calculations or display purposes as needed.

7. Converting a string to a date or time object

date_from_string = datetime.datetime.strptime(date_string, "Format")

Example

import datetime

date_string = "2023-07-11"

# Converting string to datetime object
date_from_string = datetime.datetime.strptime(date_string, "%Y-%m-%d")

In this example, the strptime() method is used to parse the date_string and convert it into a datetime object. The format string “%Y-%m-%d” specifies the expected format of the string, where %Y represents the year, %m represents the month, and %d represents the day. You can modify the format string based on the format of your input date string.

After executing this code, the date_from_string variable will store the converted datetime object based on the provided date string.

8. Accessing different components of a date or time object

year = date_obj.year
month = date_obj.month
day = date_obj.day
hour = time_obj.hour
minute = time_obj.minute
second = time_obj.second

In this example, the .year, .month, and .day attributes are used to access the year, month, and day components of the date_obj object, respectively. Similarly, the .hour, .minute, and .second attributes are used to access the hour, minute, and second components of the time_obj object, respectively.

9. Displaying a formatted date and time

print(formatted_date)
print(formatted_time)

When executed, this code will output the formatted date and time stored in the formatted_date and formatted_time variables, respectively.

10. Comparing dates and times

import datetime

# Creating datetime objects
datetime_obj1 = datetime.datetime(2023, 7, 11, 10, 30, 0)
datetime_obj2 = datetime.datetime(2023, 7, 12, 9, 15, 0)

# Comparing dates
if datetime_obj1.date() == datetime_obj2.date():
    print("The dates are the same.")
elif datetime_obj1.date() > datetime_obj2.date():
    print("datetime_obj1 is a later date.")
else:
    print("datetime_obj2 is a later date.")

# Comparing times
if datetime_obj1.time() == datetime_obj2.time():
    print("The times are the same.")
elif datetime_obj1.time() > datetime_obj2.time():
    print("datetime_obj1 is a later time.")
else:
    print("datetime_obj2 is a later time.")

In this example, I have created datetime_obj1 and datetime_obj2 with specific date and time values for comparison. You can modify the datetime values according to your requirements.

The code compares the dates and times using the .date() and .time() methods, respectively and prints the corresponding messages based on the comparison results.

11. Calculating the difference between dates and times

import datetime

# Assuming you have already defined datetime_obj1 and datetime_obj2

# Calculating the difference between dates
date_difference = datetime_obj1.date() - datetime_obj2.date()
print("Date difference:", date_difference.days, "days")

# Calculating the difference between times
time_difference = datetime.datetime.combine(datetime.date.min, datetime_obj1.time()) - datetime.datetime.combine(datetime.date.min, datetime_obj2.time())
print("Time difference:", time_difference)

# Calculating the difference between datetimes
datetime_difference = datetime_obj1 - datetime_obj2
print("Datetime difference:", datetime_difference)

In this example, we calculate the time difference by combining the time objects with a minimal date and then subtracting them as datetime objects. This allows us to obtain the accurate time difference.

12. Working with time zones

Working with time zones in Python can be achieved using the pytz library in combination with the datetime module.

import datetime
import pytz

# Get the current datetime in UTC
current_datetime_utc = datetime.datetime.now(pytz.UTC)
print("Current datetime in UTC:", current_datetime_utc)

# Convert the current datetime to a specific time zone
desired_timezone = pytz.timezone('America/New_York')
current_datetime_timezone = current_datetime_utc.astimezone(desired_timezone)
print("Current datetime in desired time zone:", current_datetime_timezone)

# Create a datetime with a specific time zone
specific_datetime = datetime.datetime(2023, 7, 11, 10, 30, tzinfo=desired_timezone)
print("Specific datetime in desired time zone:", specific_datetime)

# Get a list of available time zones
available_timezones = pytz.all_timezones
print("Available time zones:")
for timezone in available_timezones:
    print(timezone)

In this example, we import the datetime and pytz modules.

To get the current datetime in UTC, we use datetime.datetime.now(pytz.UTC).

To convert the current datetime to a specific time zone, we use the astimezone() method and provide the desired time zone using pytz.timezone(‘America/New_York’) as an example.

To create a datetime with a specific time zone, we pass the desired timezone using the tzinfo parameter when creating the datetime object.

Finally, we can use pytz.all_timezones to get a list of available time zones.

You can modify the example based on your specific requirements, such as choosing a different time zone or using a different datetime value.

A real-world example of the flight booking system

import datetime
import pytz

# Flight Schedule
departure_time = datetime.datetime(2023, 7, 11, 10, 30)
arrival_time = datetime.datetime(2023, 7, 11, 15, 45)

# Timezone Conversion
departure_zone = pytz.timezone('America/New_York')
arrival_zone = pytz.timezone('Europe/London')
departure_time_local = departure_time.astimezone(departure_zone)
arrival_time_local = arrival_time.astimezone(arrival_zone)

# Flight Duration
flight_duration = arrival_time - departure_time

# Booking Time Validation
booking_cutoff_time = datetime.time(23, 59)  # Assuming booking cutoff is 11:59 PM
current_time = datetime.datetime.now().time()
is_valid_booking = current_time <= booking_cutoff_time

# Flight Delay Handling
departure_time += datetime.timedelta(minutes=30)  # Adding a 30-minute delay

# Printing Results
print("Departure Time (Local):", departure_time_local)
print("Arrival Time (Local):", arrival_time_local)
print("Flight Duration:", flight_duration)
print("Is Booking Valid:", is_valid_booking)
print("Updated Departure Time (with delay):", departure_time)

Output:

Departure Time (Local): 2023-07-11 06:30:00-04:00
Arrival Time (Local): 2023-07-11 16:45:00+01:00
Flight Duration: 5:15:00
Is Booking Valid: True
Updated Departure Time (with delay): 2023-07-11 11:00:00
  • We define the departure and arrival times as datetime objects to represent the flight schedule.
  • We specify the desired time zones (America/New_York and Europe/London) using the pytz.timezone function and convert the departure and arrival times to the respective local time zones using astimezone.
  • We calculate the flight duration by subtracting the departure time from the arrival time.
  • We define a booking cutoff time and compare it with the current time to determine if a booking is valid.
  • We simulate a flight delay by adding a 30-minute delay to the departure time using datetime.timedelta.
  • Finally, we print the results, including the local departure and arrival times, flight duration, booking validity, and the updated departure time with the delay.

Photo by Jordan Benton

Leave a Comment