Monday, November 18, 2024
Google search engine
HomeLanguagesWorking With Dates in Python

Working With Dates in Python

In this article, we will discuss how to work with dates using python.

Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed.  By using this module, You will get the time and date from the timezone that your local computer is present. This module just gets the date and time from the host computer ( Which in this case, it is your computer from which the program is executed ).

Date Class

Before diving into in-depth functions. Let’s start with a simple program that returns today’s date using the date object in the datetime module.

Syntax: 

date.today()

Example: Get current date

Python3




# importing the module
from datetime import date
  
# storing today's date in a variable
today = date.today()
  
# Printing the variable
print(f"Today's date: {today}")


Output:

Today’s date: 2021-09-28

today() method will give you the present date of your timezone. If you need just the year or month or day then you can use this method with the respective keywords.

Example: Getting date attribute wise

Python3




from datetime import date
  
today = date.today()
  
# to print the present year
print(f"Present Year:{today.year}")
  
# to print the present month
print(f"Present Month:{today.month}")
  
# to print the present date
print(f"Present Date:{today.day}")


Output:

Present Year:2021
Present Month:9
Present Date:28

Example: Program to count the number of days from the present date to a specific day 

Python3




# Importing date from Datetime module
from datetime import date
  
# Storing today's date into a variable
today = date.today()
  
# Storing the specific date
graduation_day = date(2023, 8, 11)
  
# finding the difference of today's date from 
# specified date
days_left = abs(graduation_day - today)
  
# Displaying the no.of.days left without time
print(f"Number of days left till graduation: {days_left}")


Output:

Number of days left till graduation: 682 days, 0:00:00

Datetime class

This method is similar to the date method but this is an upgraded version of the date object which will get you both the date and time from your local system. Let’s write the same program, which we wrote for the date object but this time to calculate the remaining days with time.

Example: Program to count remaining days

Python3




from datetime import datetime
  
# By using now(), We will get both current 
# date and time Storing current time and
# date into a variable
today = datetime.now()
  
# Storing the date and time you want to calculate
# In this you have to give the time as the input
graduation_day = datetime(2023, 8, 11, 0, 0, 0)
  
# finding the difference from
days_left = abs(graduation_day - today)
  
# Displaying the no.of.days left with time
print(f"Time left till the graduation: {days_left}")


Output:

Time left till the graduation: 681 days, 22:12:03.851113

Timedelta class

This object allows us to add or subtract time or date to a specific date and time.

Syntax : 

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Example: Adding and subtracting time 

Python3




from datetime import datetime, timedelta
  
# adding 9 hours
hour_delta = timedelta(hours=9)
  
# Storing the new date
timeAdded = datetime.now() + hour_delta
  
# Displaying current date and time with 
# adding 9 hours
print(f"The date after adding 9 hours: {timeAdded}")
  
# adding 1 day
day_delta = timedelta(days=1)
  
# storing the new date
dateAdded = datetime.now() + day_delta
  
# Displaying current date and time with 
# adding 1 day
print(f"The date after adding 1 day: {dateAdded}")


Output:

The date after adding 9 hours: 2021-09-28 10:49:39.577570

The date after adding 1 day: 2021-09-29 01:49:39.577570

Parsing and formatting

If we want to convert the dates into readable strings, strftime() method is used.

Syntax:

time.strftime(format, t)

Parameters:

  • format – This is of string type. i.e. the directives can be embedded in the format string.
  • t – the time to be formatted.

Example: Converting date to string

Python3




import datetime
  
today = datetime.datetime(2021, 9, 10, 12, 30, 30)
  
print(today.strftime("%H:%M:%S %B %d %Y"))


Output:

12:30:30 September 10 2021

Parsing is used to convert a string into datetime format. strptime() is used to perform this. The parameters are date_string and format respectively.

Syntax : 

strptime(date_string, format)

Example: Convert datetime to string

Python3




from datetime import datetime
  
print(datetime.strptime('26/5/2020', '%d/%m/%Y'))


Output:

2020-05-26 00:00:00

RELATED ARTICLES

Most Popular

Recent Comments