50

How can I convert os.path.getctime() to the right time?

My source code is:

import os

print("My Path: "+os.getcwd())
print(os.listdir("."))
print("Root/: ",os.listdir("/"))


for items in os.listdir("."):
    if os.path.isdir(items):
        print(items+" "+"Is a Directory")
        print("---Information:")
        print("    *Full Name: ",os.path.dirname(items))
        print("    *Created Time: ",os.path.getctime(items))
        print("    *Modified Time: ",os.path.getmtime(items))
        print("    *Size: ",os.path.getsize(items))
    else:
        print(items+" Is a File")

Output:

---Information:
    *Full Name:  
    *Created Time:  1382189138.4196026
    *Modified Time:  1382378167.9465308
    *Size:  4096
peterh
  • 11,875
  • 18
  • 85
  • 108
Iem-Prog
  • 593
  • 1
  • 5
  • 9

5 Answers5

108

I assume that by right time you mean converting timestamp to something with more meaning to humans. If that is the case then this should work:

>>> from datetime import datetime
>>> datetime.fromtimestamp(1382189138.4196026).strftime('%Y-%m-%d %H:%M:%S')
'2013-10-19 16:25:38'
Kristaps Taube
  • 2,363
  • 1
  • 17
  • 17
  • Depending your use case, you might want to replace complex .strftime(...) by simplier .isoformat() and gain ms information – comte May 20 '22 at 12:36
6

I was looking for the same problem, and resolv indirectly it with the help of answers. So a solution :

import os
import time
import datetime

# FILE_IN a file...

file_date = time.ctime(os.path.getmtime(FILE_IN))
file_date = datetime.datetime.strptime(file_date, "%a %b %d %H:%M:%S %Y")
print("Last modif: %s" % file_date.strftime('%Y-%m-%d %H:%M:%S'))

With this solution : a date object with the good value, an example of conversion to see it (with the good string format to insert in a mysql database).

Mih Zam
  • 1,411
  • 1
  • 12
  • 12
  • Thank you! This was what I was looking for. It can be modified to something like "20221214". – Moses Dec 14 '22 at 05:12
5

You can also use ctime function from the time module.

import os
import time

c_time = os.path.getctime(r'C:\test.txt')
print(c_time)
print(time.ctime(c_time))

Output:

1598597900.008945
Fri Aug 28 09:58:20 2020
filler36
  • 456
  • 7
  • 13
2

From the documentation

The return value is a number giving the number of seconds since the epoch (see the time module)

And in the time module we see localtime()

Use the following functions to convert between time representations:

...

| seconds since the epoch | struct_time in local time | localtime() |

And from there use strftime() to get the format you want

CivFan
  • 13,560
  • 9
  • 41
  • 58
CDspace
  • 2,639
  • 18
  • 30
  • 36
0
>>> from datetime import date
>>> date.fromtimestamp(path.getatime("/Users"))
    datetime.date(2015, 3, 10)
Yang Wang
  • 580
  • 4
  • 14