Working with Dates and Times in Python


Manipulating date and time is an integral part of any programming language. Python has standard library containing the datetime module which has nearly all the features and functions to implement the calculations involving date and time. In the below examples we will see how the various aspects of date time is implemented.

Handling the Current Date

The datetime module has a class named datetime. We can import this class and use its functions to create a datetime object. Then apply various formatting techniques to display the date and time values. So first we create a datetime object initialized with now() function. This object holds all parts of the current date and time and then we manipulate different parts of it.

Example

 Live Demo

from datetime import datetime
dt_time_obj = datetime.now()
# Print the current date time
print(dt_time_obj)
# Find the object class
print('Object Class :- ',type(dt_time_obj))

Output

Running the above code gives us the following result −

2020-01-22 09:33:02.693863
Object Class :-

Datetime and Strings

We can convert strings to datetime and datetime to strings using the methods strptime and strftime. This conversion is a necessity when we handle different data sources where the data may not be presented in the exact format as needed by python to be called as date time. In the below example we take a string and convert it to date time. And also do the opposite action.

Example

 Live Demo

from datetime import datetime
dt_string = '2020-1-30 2-52-59'

# Create date object from String
date_val = datetime.strptime(dt_string, "%Y-%m-%d %H-%M-%S")

print(date_val)
print('Class: ',type(date_val))
print("\n")
# Create String from Date Object
date_val_str = datetime.strftime(date_val, "%Y-%m-%d %H-%M-%S")
print(date_val_str)
print('Class: ',type(date_val_str))

Output

Running the above code gives us the following result −

2020-01-30 02:52:59
Class:
2020-01-30 02-52-59
Class:

Extracting Parts of a Date Time Value

We can extract different parts of the date using directives and the strftime method. Below is a list of some examples on the different directives and their purpose. For a complete list of all the directives, please refer the python documentation here.

Directive
Usage
%A
Weekday
%B
Month
%M
Minutes
%Y
Year
%d
Day of the Month

The below example shows how the directives are used.

Example

 Live Demo

from datetime import datetime
dt_string = '2020-1-30 2-52-59'
# Create date object from String
date_val = datetime.strptime(dt_string, "%Y-%m-%d %H-%M-%S")
#Return the year and name of weekday, month,Day of month:
print(date_val.year)
print(date_val.strftime("%d"))
print(date_val.strftime("%B"))
print(date_val.strftime("%A"),"\n")

Output

Running the above code gives us the following result −

2020
30
January
Thursday

Date Time Arithmetic

Next we see examples on calculations involving date and time. We can add and subtract days, hours etc from a given date. Also we can take to dates as inputs and apply various operations on them.

Using TimeDelta

Example

 Live Demo

#import datetime
from datetime import *

# Find current time
dt_time_today = datetime.now()
print ("Today's date: ", str(dt_time_today))

#add 5 days to current
new_date = dt_time_today + timedelta(days = 5)
print('After 5 days: ', new_date)

#Remove 2 weeks from current date
two_weeks_back = dt_time_today - timedelta(weeks = 2)
print('Two weeks ago: ', two_weeks_back)
print('two_weeks_back object type: ', type(two_weeks_back))

Output

Running the above code gives us the following result −

Today's date: 2020-01-29 12:38:03.290795
After 5 days: 2020-02-03 12:38:03.290795
Two weeks ago: 2020-01-15 12:38:03.290795
two_weeks_back object type:

Using Operators

We can apply some operators between two dates. The difference in dates can be found out using the minus operator and the dates can be compared using the logical operator.

Example

 Live Demo

from datetime import datetime

# Given Dates
date1 = datetime(2018,5, 12, 8, 11, 53)
date2 = datetime(2017, 6, 16, 12, 43, 27)

# Difference between two dates
date_diff = date1-date2
print("Difference: ", date_diff)

# Comparing two dates
print(date1 < date2)

Output

Running the above code gives us the following result −

Difference: 329 days, 19:28:26
False
raja
Published on 04-Feb-2020 06:32:59
Advertisements