find the creation date of a json file in python

To find the creation date of a file in Python, you can make use of the os.path.getctime() function from the os module. Here's an example code snippet to find the creation date of a JSON file:

main.py
import os
import json
from datetime import datetime

filename = 'example.json'

try:
    # Get the creation time of the file
    creation_time = os.path.getctime(filename)

    # Convert the timestamp to a datetime object
    dt_object = datetime.fromtimestamp(creation_time)

    # Print the datetime object in a human-readable format
    print("The file {} was created on {}".format(filename, dt_object))

except FileNotFoundError:
    print(f"File not found: {filename}")

except:
    print("An error occurred while reading the file.")
539 chars
22 lines

In this example, we first import the necessary modules - os, json, and datetime. We then define the filename of the JSON file we want to check.

Using a try-except block, we attempt to retrieve the creation time of the file with os.path.getctime(). If the file is found, we convert the timestamp to a datetime object with the datetime.fromtimestamp() method. Finally, we print the filename and creation time in a human-readable format.

Note that exceptions are caught for FileNotFoundError and general errors to avoid program crashes.

gistlibby LogSnag