0

I got the creation time of a file using this command:

ctime = Path("/home/user/mypic.jpg").stat().st_ctime

How do I convert this info to a datetime.datatime object that is human-readable? I tried this answer but it failed:

from datetime import datetime
datetime.strptime(str(ctime), "%a %b %d %H:%M:%S %Y") 
Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • "I tried this answer but it failed:" - **What happened** when you tried it? **How is that different** from what you expect to happen? **Did you try to check** the result from `ctime` before attempting this method? When you looked up the answer, **what was your understanding** of the **specific** problem it is trying to solve? (Specifically: **what happens** when you try using `time.ctime()`? Does that look like the result you get for `ctime` in your code?) What do you think the value in your code actually represents? ([Did you try](https://meta.stackoverflow.com/questions/261592) to find out?) – Karl Knechtel Feb 14 '23 at 10:03
  • Your account is 7 years old and you have 11 gold badges - all for asking questions - so I shouldn't have to explain these fundamental things about asking questions to you. Please try to study problems before asking about them, and look for existing solutions by *making sure you have an accurate picture of the problem*. We don't provide a debugging service. See also https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ as a useful resource. – Karl Knechtel Feb 14 '23 at 10:05

1 Answers1

1

.st_ctime returns epoch seconds, so first convert it to a datetime object with fromtimestamp, and then use strftime to convert to a string

from pathlib import Path
from datetime import datetime

ctime = Path("...").stat().st_ctime
dt = datetime.fromtimestamp(ctime)  # convert from epoch timestamp to datetime
dt_str = datetime.strftime(dt, "%a %b %d %H:%M:%S %Y")  # format the datetime
print(dt_str)

strptime is the opposite, it takes a formatted string and converts it back to a datetime object

>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
Sean Breckenridge
  • 1,932
  • 16
  • 26