How can I convert os.path.getctime()?

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
1

5 Answers

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'
1

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

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).

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

>>> from datetime import date
>>> date.fromtimestamp(path.getatime("/Users")) datetime.date(2015, 3, 10)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like