Home > Enterprise >  How can I get the creation timestamp of a file which is in a folder ? [python] [csv]
How can I get the creation timestamp of a file which is in a folder ? [python] [csv]

Time:09-16

I want to get only one creation timestamp of any file in a folder because they all were created at the same time. When I use this code below, it only shows the timestamp of the folder but not the file. There are many folder with many files and the folder were created newer dates.

c_time = os.path.getctime(path)
dt_c = datetime.datetime.fromtimestamp(c_time)

CodePudding user response:

    import os
    import platform

from datetime import datetime, timezone

def creation_date(path_to_file):
    if platform.system() == 'Windows':
       return os.path.getctime(path_to_file)
    else:
       stat = os.stat(path_to_file)
       try:
          # return stat.st_birthtime
          return datetime.fromtimestamp(stat.st_birthtime, tz=timezone.utc)
       except AttributeError:           
          # return stat.st_mtime
          return datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc)


date_creation = creation_date('/home/henro/Documents/help/app/main.py')

print (date_creation)
output:
2022-09-16 08:44:18.115245 00:0

change the path_file to yours

CodePudding user response:

os.path.getctime() method in Python is used to get the system’s ctime of the specified path I guess you did right. test.txt Is on my current folder

import os
import datetime
path = 'test.txt'
c_time = os.path.getctime('test.txt')
dt_c = datetime.datetime.fromtimestamp(c_time)
print(dt_c)

Output:

2022-09-16 10:28:29.922116

If you want to find when your file was last modified, you can use os.path.getmtime()

import os
import datetime
m_time = os.path.getmtime(path)
dt = datetime.datetime.fromtimestamp(m_time)
print('Modified on:', dt)

Output:

Modified on: 2022-09-16 10:38:58.934354

Edited to reflect the comments If you want to get the timestamp of all the files in a folder, you have to list all of them first. You can do it with the help of os.listdir() The do something like this

dir_list = os.listdir(yourpathhere)
for f in dir_list[1:]:
    print("filename {}".format(f))
    c_time = os.path.getctime(f)
    dt_c = datetime.datetime.fromtimestamp(c_time)
    print("Creation date {}".format(dt_c))
    m_time = os.path.getmtime(path)
    dt = datetime.datetime.fromtimestamp(m_time)
    print('Modified on {}'.format(dt))

Output:

2022-09-16 10:38:58.934354
Modified on: 2022-09-16 10:38:58.934354
filename test.txt
Creation date 2022-09-16 10:38:58.934354
Modified on 2022-09-16 10:38:58.934354
filename test_2.py
Creation date 2022-09-16 11:02:29.505548
Modified on 2022-09-16 10:38:58.934354
  • Related