Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Format Ctime Method

Tags:

python

date

time

I am trying to get a the modified date of a file using os.path.getmtime() and to convert time into human readable format; it is advised to use time.ctime() method but it gives the name of the date and month too, which I do not want.

Is it possible to format %d %m %Y, %H:%M?

Currently I have code like:

import os.path, time

path = #path of the file

print time.ctime(os.path.getmtime(path))
like image 589
MertTheGreat Avatar asked Sep 11 '25 07:09

MertTheGreat


1 Answers

You can do that with datetime.fromtimestamp() like:

Code:

file_time_string = dt.datetime.fromtimestamp(os.path.getmtime(__file__))

Test Code:

import os
import datetime as dt

file_time = dt.datetime.fromtimestamp(os.path.getmtime(__file__))
print(file_time.strftime("%d %m %Y, %H:%M"))

Results:

24 03 2018, 16:39
like image 161
Stephen Rauch Avatar answered Sep 12 '25 22:09

Stephen Rauch