28

I'm trying to get the datestamp on the file in mm/dd/yyyy format

time.ctime(os.path.getmtime(file))

gives me detailed time stamp Fri Jun 07 16:54:31 2013

How can I display the output as 06/07/2013

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ank
  • 6,040
  • 22
  • 67
  • 100

3 Answers3

54

You want to use time.strftime() to format the timestamp; convert it to a time tuple first using either time.gmtime() or time.localtime():

time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
6
from datetime import datetime
from os.path import getmtime

datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')
Magisch
  • 7,312
  • 9
  • 36
  • 52
Michael
  • 71
  • 1
  • 1
  • 2
    Welcome to Stack Overflow! While this piece of code may answer the question, it is better to include a description of what the problem was, and how your code will tackle the given problem. For the future, here is some information, how to crack a awesome answer on Stack Overflow: http://stackoverflow.com/help/how-to-answer – dirtydanee Nov 08 '16 at 14:47
1

You can create the datetime object using the ctime str like you mention and then format it back to a string of any format.

str1 = time.ctime(os.path.getmtime(file)) # Fri Jun 07 16:54:31 2013
datetime_object = datetime.strptime(str1, '%a %b %d %H:%M:%S %Y')
datetime_object.strftime("%m/%d/%Y") # 06/07/2013

This way you don't have to deal with timezones + absolute timestamp from the Epoch

Credit: Converting string into datetime

Linking: How to get file creation & modification date/times in Python?

http://strftime.org/

storm_m2138
  • 2,281
  • 2
  • 20
  • 18