Open In App

Python PIL save file with datetime as name

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to see how to save image files with datetime as a name using PIL Python.

Modules required:

PIL: This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities.

pip install Pillow

datetime: This module helps us to work with dates and times in Python.

pip install datetime

os: This module provides a portable way of using operating system-dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.

Stepwise implementation:

Step 1: Open the image using Image module with the provided path.

img = Image.open(path)

Step 2: Get the current DateTime using datetime.now() and format the date and time using strftime().

curr_datetime = datetime.now().strftime('%Y-%m-%d %H-%M-%S')

Step 3: Split the path using os.path.splitext(path) into root and extension.

splitted_path = os.path.splitext(picture_path)

Step 4: Add the current datetime in between root and extension and concatenate them.

modified_picture_path = splitted_path[0] + curr_datetime + splitted_path[1]

Step 5: Save the image with the modified path using Image module.

img.save(modified_picture_path)

Below is the full implementation:

Python3
# Import the required modules
import os
from PIL import Image
from datetime import datetime


# Main function
if __name__ == '__main__':

    picture_path = "image.jpg"

    # Open the image using image module from PIL library
    img = Image.open(picture_path)

    # Get the current date and
    # time from system
    # and use strftime function
    # to format the date and time.
    curr_datetime = datetime.now().strftime('%Y-%m-%d %H-%M-%S')

    # Split the picture path
    # into root and extension
    splitted_path = os.path.splitext(picture_path)

    # Add the current date time
    # between root and extension
    modified_picture_path = splitted_path[0] +
    curr_datetime + splitted_path[1]

    # Save the image with modified_picture_path
    img.save(modified_picture_path)

Output:


Practice Tags :

Similar Reads