Python PIL save file with datetime as name

Python PIL Saving Files with Datetime Names

In this article, we’ll see how to use Python’s PIL to save image files with datetime names.

Required Modules:

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

pip install Pillow

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

pip install datetime

os: This module provides a portable way to use operating system-dependent functionality. The os and os.path modules include many functions for interacting with the file system.

Step by Step:

Step 1: Open the image using the _Image _ module and provide the 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: Use os.path.splitext(path) to split the path into root and extension.

splitted_path = os.path.splitext(picture_path)

Step 4: Add the current date and time between the root and extension directories and concatenate them.

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

Step 5: Use the _Image _ module to save the image using the modified path.

img.save(modified_picture_path)

Below is the complete implementation.

# 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:

Python PIL saves files with date and time as names

Leave a Reply

Your email address will not be published. Required fields are marked *