Explain Dates in Python
In this article, we’ll explore how to handle dates in Python. Python simplifies working with dates and times through a built-in module called DateTime. This module provides efficient ways to work with dates without needing complex programming. When you import DateTime, you can easily access the current time and date based on your computer’s timezone. Essentially, the module fetches the date and time from the computer where your program is running.
Date Class
Before we get into more detailed functions, let’s begin with a basic program that simply gives us today’s date. We’ll use the ‘date’ object from the ‘datetime’ module for this.
Example
# Importing the necessary module
from datetime import date
# Storing today's date in a different variable
current_date = date.today()
# Printing the variable
print(f"Today's date: {current_date}")
Output
Today’s date: 2024-02-08
The ‘today()’ method provides the current date in your timezone. If you only need the year, month, or day separately, you can use this method along with the corresponding keywords.
For example, to get the date attributes separately:
from datetime import date
current_date = date.today()
# Printing the present year
print(f"Present Year: {current_date.year}")
# Printing the present month
print(f"Present Month: {current_date.month}")
# Printing the present date
print(f"Present Date: {current_date.day}")
Output
Present Year: 2024
Present Month: 2
Present Date: 8
Example
Program to calculate the number of days from today’s date to a specified date.
from datetime import date
# Storing today's date into a variable
current_date = date.today()
# Storing the specific date
graduation_date = date(2023, 8, 11)
# Finding the difference between today's date and the specified date
days_left = abs(graduation_date - current_date)
# Displaying the number of days left without considering time
print(f"Number of days left till graduation: {days_left}")
Output
Number of days left till graduation: 181 days, 0:00:00
Datetime class
This method works like the date method, but it’s an enhanced version that retrieves both the date and time from your local system.
Let’s rewrite the same program we did for the date object, but this time, we’ll calculate the remaining days along with the time.
Example
# Importing date from the Datetime module
from datetime import datetime
# Storing current date and time into a variable
current_date_time = datetime.now()
# Storing the date and time you want to calculate
# In this you have to give the time as the input
graduation_date_time = datetime(2023, 8, 11, 0, 0, 0)
# finding the difference
time_left = abs(graduation_date_time - current_date_time)
# Displaying the time left till graduation
print(f"Time left till graduation: {time_left}")
Output
Time left till graduation: 185 days, 3:41:31.882946
Timedelta class
This tool lets us add or take away time or dates from a particular date and time.
Syntax
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example
from datetime import datetime, timedelta
# Adding 9 hours
hour_difference = timedelta(hours=9)
# Storing the updated time
updated_time = datetime.now() + hour_difference
# Displaying the current date and time after adding 9 hours
print(f"The date after adding 9 hours: {updated_time}")
# Adding 1 day
day_difference = timedelta(days=1)
# Storing the updated date
updated_date = datetime.now() + day_difference
# Displaying the current date and time after adding 1 day
print(f"The date after adding 1 day: {updated_date}")
Output
The date after adding 9 hours: 2024-02-12 12:55:34.076753
The date after adding 1 day: 2024-02-13 03:55:34.078244
Parsing and formatting
When we want to turn dates into readable strings, we use the strftime() method
Syntax
time.strftime(format, t)
Parameters
- format – This is a string type representing the format in which the time will be displayed.
- t – Refers to the time that will be formatted.
Example
import datetime
selected_date = datetime.datetime(2022, 10, 9, 11, 20, 10)
print(selected_date.strftime("%H:%M:%S %B %d %Y"))
Output
11:20:10 October 09 2022
Parsing
Parsing is the process of converting a string into a datetime format. This is done using the strptime() method. Its parameters are the date string and the format, respectively.
Syntax
strptime(date_string, format)
Example
from datetime import datetime formatted_date = datetime.strptime('12/2/2024', '%d/%m/%Y') print(formatted_date)
Output
2024-02-12 00:00:00
Conclusion
Python provides powerful tools within the datetime module for handling dates and times efficiently. Through this module, you can manipulate dates, calculate time differences, format dates into readable strings, and parse strings into datetime objects. Understanding these functionalities allows for precise date and time handling in Python programming.