Alright ! Let’s dive deep into Python datetime and learn how to handle dates and times like a pro. In this tutorial, we’ll cover everything from creating date objects using the datetime() constructor to formatting them with strftime(). We’ll also explore some useful methods for extracting specific parts of dates and comparing them.
First let’s import the datetime module:
# Import the datetime module from the standard library
from datetime import datetime, timedelta
# Create a datetime object using the current date and time
current_datetime = datetime.now()
# Create a timedelta object representing a time interval of 1 day
one_day = timedelta(days=1)
# Use the timedelta object to calculate a new datetime object
# by adding 1 day to the current datetime
next_day = current_datetime + one_day
# Print the current datetime and the next day
print("Current datetime:", current_datetime)
print("Next day:", next_day)
# Create a datetime object for a specific date and time
specific_datetime = datetime(2021, 1, 1, 12, 30, 0)
# Format the datetime object using strftime()
formatted_datetime = specific_datetime.strftime("%B %d, %Y at %I:%M %p")
# Print the formatted datetime
print("Formatted datetime:", formatted_datetime)
# Extract specific parts of the datetime object
year = specific_datetime.year
month = specific_datetime.month
day = specific_datetime.day
hour = specific_datetime.hour
minute = specific_datetime.minute
second = specific_datetime.second
# Print the extracted parts
print("Year:", year)
print("Month:", month)
print("Day:", day)
print("Hour:", hour)
print("Minute:", minute)
print("Second:", second)
# Compare two datetime objects
if specific_datetime > current_datetime:
print("The specific datetime is in the future.")
else:
print("The specific datetime is in the past.")
Now we can create a date object using the datetime() constructor. For example, to create January 2nd, 2022 at midnight (because who needs sleep anyway?), use this code:
# Create a date object using the datetime() constructor
# The datetime() constructor takes in parameters for year, month, and day
# and returns a datetime object representing that date
my_date = datetime(year=2022, month=1, day=2)
# Print the datetime object
# The print() function outputs the value of the given object
# In this case, it outputs the datetime object in the format 'YYYY-MM-DD HH:MM:SS'
print(my_date)
No more messing around with string manipulation or trying to parse dates from a text file. The datetime module does all the heavy lifting for you!
Next, let’s add and subtract time spans using timedelta(). Let’s say we want to add 1 week (7 days) to our date object:
# Import the datetime module to use its functions
import datetime
# Create a date object using the current date
my_date = datetime.date.today()
# Use timedelta() to add 7 days to the date object
new_date = my_date + datetime.timedelta(days=7)
# Print the new date object
print(new_date) # Outputs something like '2022-01-09 00:00:00'
# The datetime module allows us to easily manipulate dates and times
# The timedelta() function adds a specified amount of time to a date object
# In this case, we are adding 7 days to the current date
# The result is stored in the new_date variable
# Finally, we print the new date object to see the updated date
Again, no need to do any math or convert between time zones. The datetime module handles all that for you!
Now let’s format our date and time objects using strftime(). This is where the real magic happens being able to customize how your dates are displayed in a string format. For example:
# Import the datetime module to handle date and time objects
import datetime
# Create a variable for today's date using the datetime module's date class
today = datetime.date.today()
# Create a variable for 7 days from today using the timedelta function from the datetime module
seven_days = datetime.timedelta(days=7)
# Create a new date object by adding 7 days to today's date
new_date = today + seven_days
# Format the date objects using strftime() to customize the display format
# %A represents the full weekday name, %B represents the full month name, and %d represents the day of the month
formatted_today = today.strftime('%A %B %d')
formatted_new_date = new_date.strftime('%A %B %d')
# Print a string using the formatted date objects
print("Today is {} and in 7 days it will be {}".format(formatted_today, formatted_new_date))
# Outputs something like 'Today is Monday January 02 and in 7 days it will be Monday January 09'
The strftime() function takes a format string as its argument, which can include all sorts of fancy formatting options. Check out the official documentation for more info!
Finally, let’s extract specific parts of dates using methods like year(), month(), day(). For example:
# This script uses the strftime() function to format a date and extract specific parts of it using methods like year(), month(), and day().
# Import the datetime module to access date and time related functions
import datetime
# Create a variable called my_date and assign it the current date using the today() method
my_date = datetime.date.today()
# Use the strftime() function to format the date and store it in a variable called formatted_date
# The format string '%Y' represents the year in four digits
formatted_date = my_date.strftime('%Y')
# Print a string with the current year using the formatted_date variable
print("The current year is {}".format(formatted_date)) # Outputs something like 'The current year is 2022'
And that’s it ! With these simple techniques, you can handle dates and times like a pro in Python. No more struggling with string manipulation or external libraries just pure, unadulterated datetime magic!
If you’d like to practice writing datetime code with interactive answer-checking, check out our Python intermediate course for a lesson on datetime in Python with interactive answer-checking and in-browser code-running.