5 Best Ways to Add Time to a Filename in Python

πŸ’‘ Problem Formulation: When working with file operations in Python, it’s a common requirement to name files with a timestamp. This ensures a unique filename and can preserve the history of file creation. The problem at hand involves appending a datetime string to a file’s base name. For instance, given an input filename ‘report.csv’, we want to generate a filename that includes the current time, like ‘report_202303021030.csv’ (indicating a timestamp of March 2, 2023, at 10:30).

Method 1: Using the datetime and strftime Functions

This method entails using the built-in datetime module, which provides functions to manipulate dates and times in both simple and complex ways. The strftime method can be used to format the datetime object as a string, making it suitable to concatenate with the original filename.

Here’s an example:

from datetime import datetime

base_filename = 'report.csv'
timestamp = datetime.now().strftime('%Y%m%d%H%M')
new_filename = f"{base_filename.split('.')[0]}_{timestamp}.{base_filename.split('.')[-1]}"

print(new_filename)

Output:

report_202303021030.csv

This snippet creates a new file name with the current date and time appended. datetime.now() gets the current time, and strftime('%Y%m%d%H%M') formats it as a string. The filename is then reconstructed with the timestamp inserted before the file extension.

Method 2: Using the time Module

The time module allows access to various time-related functions. Using the time.strftime() function, we can directly generate a formatted time string, which can be appended to the file name.

Here’s an example:

import time

base_filename = 'report.csv'
timestamp = time.strftime('%Y%m%d%H%M')
new_filename = f"{base_filename.rsplit('.', 1)[0]}_{timestamp}.{base_filename.rsplit('.', 1)[-1]}"

print(new_filename)

Output:

report_202303021030.csv

This code block formats the current time as a string with time.strftime() and stitches the string with the base filename, placing the timestamp before the extension, resulting in a new file name with a timestamp.

Method 3: Using Python’s os.path Functions

The os.path module in Python provides methods for manipulating file paths. This method combines os.path.splitext() with datetime to insert the timestamp into the filename.

Here’s an example:

import os
from datetime import datetime

base_filename = 'report.csv'
filename, file_extension = os.path.splitext(base_filename)
timestamp = datetime.now().strftime('%Y%m%d%H%M')
new_filename = f"{filename}_{timestamp}{file_extension}"

print(new_filename)

Output:

report_202303021030.csv

Using os.path.splitext() to separate the file name from the extension provides a clean approach to insert the timestamp. It avoids any errors with filenames containing multiple periods.

Method 4: Using a Custom Formatting Function

Creating a custom function to handle datetime formatting and file naming provides a reusable, clean, and encapsulated approach. Such functions allow for greater flexibility and can be easily extended or modified for different timestamp formats.

Here’s an example:

from datetime import datetime

def add_timestamp_to_filename(filename, time_format='%Y%m%d%H%M'):
    base, ext = filename.rsplit('.', 1)
    timestamp = datetime.now().strftime(time_format)
    return f"{base}_{timestamp}.{ext}"

base_filename = 'report.csv'
new_filename = add_timestamp_to_filename(base_filename)

print(new_filename)

Output:

report_202303021030.csv

This code defines a function, add_timestamp_to_filename, which takes a filename and an optional time format, and returns a new filename with a timestamp. Such a function encapsulates the logic and can be reused throughout the codebase.

Bonus One-Liner Method 5: Using pathlib and datetime

The pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Combined with the datetime module, it allows for a one-line solution to the problem.

Here’s an example:

from datetime import datetime
from pathlib import Path

base_filename = Path('report.csv')
new_filename = base_filename.with_name(f"{base_filename.stem}_{datetime.now().strftime('%Y%m%d%H%M')}{base_filename.suffix}")

print(new_filename)

Output:

report_202303021030.csv

This one-liner uses the Path object’s with_name method and string interpolation to achieve the desired filename formatting efficiently.

Summary/Discussion

Each method serves the purpose of adding a timestamp to a filename in Python, but they come with different trade-offs:

  • Method 1: Using datetime and strftime. Strengths: straightforward, customizable time format. Weaknesses: Requires string manipulation of the filename.
  • Method 2: Using the time module. Strengths: simple and uses a standard library. Weaknesses: potentially less readable due to direct string manipulation.
  • Method 3: Using Python’s os.path functions. Strengths: cleanly separates filename components, less prone to errors with filenames that have multiple dots. Weaknesses: slightly more verbose.
  • Method 4: Using a custom formatting function. Strengths: encapsulates functionality, reusable, flexible. Weaknesses: requires additional code, may be overkill for a simple task.
  • Bonus Method 5: Using pathlib and datetime. Strengths: elegant one-liner with modern Python libraries. Weaknesses: requires familiarity with the pathlib module.