Datetime Operations#

handling date and time related operations is a frequent task in data science. Python has a module named datetime to work with dates and times. Let’s see various methods to perform date and time operations in Python.

Datetime module#


Current datetime#

# Example 1: Get Current Date and Time

import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)
2024-08-31 12:58:04.029138

Current date#

# Example 1: Get Current Date 

from datetime import date

datetime_object = date.today()
print(datetime_object)

# When you run the program, the output will be something like below:
2024-08-31

Datetime components#

from datetime import datetime

a = datetime(2017, 11, 28, 23, 55, 59, 342380)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())
year = 2017
month = 11
hour = 23
minute = 55
timestamp = 1511893559.34238

Time delta#

# Example 11: Difference between two dates and times

from datetime import datetime, date

t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)

t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5
print("t6 =", t6)

print("type of t3 =", type(t3)) 
print("type of t6 =", type(t6))  

# When you run the program, the output will be like below:
t3 = 201 days, 0:00:00
t6 = -333 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>

Datetime format#


The way date and time is represented may be different in different places.

It’s more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.

Python has strftime() and strptime() methods to handle this.

strftime()#

The method creates a formatted string from a given date, datetime or time object.

# Example 15: Format date using strftime()

from datetime import datetime

# current date and time
now = datetime.now()

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

# When you run the program, the output will be like below:
time: 13:04:47
s1: 08/31/2024, 13:04:47
s2: 31/08/2024, 13:04:47

Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.

Directive

Meaning

Example

%Y

year

[0001,…, 2018, 2019,…, 9999]

%m

month

[01, 02, …, 11, 12]

%d

day

[01, 02, …, 30, 31]

%H

hour

[00, 01, …, 22, 23]

%M

minute

[00, 01, …, 58, 59]

%S

second

[00, 01, …, 58, 59]

strptime()#

The method converts a formatted string into a date, datetime or time object.

# Example 16: strptime()

from datetime import datetime

date_string = "21 June, 2018"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

# When you run the program, the output will be like below:
date_string = 21 June, 2018
date_object = 2018-06-21 00:00:00

time module#


Python has a module named time to handle time-related tasks. To use functions defined in the module, we need to import the module first. Here’s how:

import time

Here are commonly used time-related functions.

time()#

The method returns the current time in seconds since the Epoch.

import time
seconds = time.time()
print("Seconds since epoch =", seconds)	

# When you run the program, the output will be something like below:
Seconds since epoch = 1725089870.415162

ctime()#

The method returns a string representing the current time in YYYY-MM-DD HH:MM:SS format.

import time

# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)

# When you run the program, the output will be something like below:
Local time: Thu Dec 27 21:19:29 2018

sleep()#

The sleep() function suspends (delays) execution of the current thread for the given number of seconds.

import time

print("This is printed immediately.")
time.sleep(2.4)
print("This is printed after 2.4 seconds.")

# When you run the program, the output will be something like below:
This is printed immediately.
This is printed after 2.4 seconds.

sleep() in multithreaded program#

The sleep() function suspends execution of the thread and process.

# Example 4: sleep() in a multithreaded program

import threading 
import time
  
def print_hello():
    for i in range(4):
        time.sleep(0.5)
        print("Hello")

def print_hi(): 
    for i in range(4): 
        time.sleep(0.7)
        print("Hi") 

t1 = threading.Thread(target=print_hello)  
t2 = threading.Thread(target=print_hi)  
t1.start()
t2.start()
Hello
Hi
Hello
Hi
Hello
Hello
Hi
Hi

👉 The above program has two threads. We have used time.sleep(0.5) and time.sleep(0.75) to suspend execution of these two threads for 0.5 seconds and 0.7 seconds respectively.