1

The title says it all. I am trying to get the year a file was created for indexing purposes. Also, I'm on windows if that matters.

SirParselot
  • 2,640
  • 2
  • 20
  • 31

3 Answers3

3

To be honest there are similar questions e.g. here

os.stat is your friend. It provides various stats on a file. Use ctime to change it into something human readable as demo'd here

import os.path, time
when = os.stat(r"path").st_ctime
time.ctime(when)
Community
  • 1
  • 1
doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

this question has been already asked, short story here, see the code below:

import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))

and here is link: How to get file creation & modification date/times in Python?

Community
  • 1
  • 1
noonewin
  • 108
  • 1
  • 8
0

so here's the solution:

import os
import datetime

#gives the create time as a unix timestamp
create_time = os.stat(<path to file>).st_ctime

#returns a datetime object
create_datetime = datetime.datetime.fromtimestamp(create_time)

#print the year
create_datetime.strftime("%Y")
Ishan Khare
  • 1,745
  • 4
  • 28
  • 59
  • No, it is not the proper solution, as st_ctime is returning the last Change time. and not Creation time – Ruchir Shukla Aug 26 '17 at 11:14
  • @RuchirShukla that's what the documentation defines it does, on unix systems - https://docs.python.org/2/library/stat.html#stat.ST_CTIME – Ishan Khare Aug 27 '17 at 14:55
  • That's exactly what I am saying."On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details)." – Ruchir Shukla Nov 04 '17 at 07:52