python - unable to use ctime to get last modified time

  • Last Update :
  • Techknowledgy :

The error message is quite clear: datetime.time has no attribute 'ctime'. But the time module has a function ctime. You are shadowing the time module by the from datetime import time line.

>>> import time
>>> time # refers to the *module*
<module 'time' from '/usr/lib/python2.7/lib-dynload/'>
   >>> time.ctime()
   'Sun Feb 1 16:23:33 2015'
   >>> from datetime import time
   >>> time # now we have a class of that name
   <type 'datetime.time'>
      >>> t = time()
      >>> t.isoformat()

I follow #1 or #2, and never #3, for exactly the reason your program didn't work:

import os
import time

modTime = time.ctime(os.path.getmtime("t.txt"))
print "t.txt was last modified at: " + modTime # This works now!

An example of #2 is:

import time
from datetime
import time as dt_time

Here are your corrected imports:

import os
from os
import path
import time
from datetime
import datetime

actually i tried it using version 3.5 and watched the tutorial about time module on youtube where the lecturer using 2.7 is the code:

from datetime
import datetime, time, timedelta
c = time.ctime(os.path.getmtime("file"))

but actually i got the error post above and the right code is:

import time
c = time.ctime(os.path.getmtime("file"))

Suggestion : 2

In this article we will discuss different ways to get the last modification date & time of a file and how to convert them into different formats.,To get the last modification time from os.stat_result object access the property ST_MTIME, that contains the time of most recent file modification in seconds. Then we can covert that to readable format using time.ctime() i.e. ,Python’s os.path module provides an another API for fetching the last modification time of a file i.e. ,Instead of time.localtime() we can also use another function datetime.fromtimestamp() to convert seconds since epoch to time object. Then we can call time.strftime() to convert that to readable format. For example,


To get the last modification time from os.stat_result object access the property ST_MTIME, that contains the time of
most recent file modification in seconds. Then we can covert that to readable format using time.ctime() i.e.

fileStatsObj = os.stat(filePath)

modificationTime = time.ctime(fileStatsObj[stat.ST_MTIME])

print("Last Modified Time : ", modificationTime)

Last Modified Time: Sun Feb 25 15: 04: 09 2018

Get last modification time using os.path.getmtime() & time.localtime()

# Get file 's Last modification time stamp only in terms of seconds since epoch 
modTimesinceEpoc = os.path.getmtime(filePath)

# Convert seconds since epoch to readable timestamp
modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))

print("Last Modified Time : ", modificationTime)

By changing format string in time.strftime() we can get date only and also in other format specific to our application i.e.

# Convert seconds since epoch to Date only
modificationTime = time.strftime('%d/%m/%Y', time.localtime(os.path.getmtime(filePath)))

print("Last Modified Time : ", modificationTime)

Suggestion : 3

Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.,Normalize the case of a pathname. On Windows, convert all characters in the pathname to lowercase, and also convert forward slashes to backward slashes. On other operating systems, return the path unchanged.,This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as strings, or bytes, or any object implementing the os.PathLike protocol.,All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned.

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])

os.path.commonpath(['/usr/lib', '/usr/local/lib'])
>>> splitdrive("c:/dir")
   ("c:", "/dir")
>>> splitdrive("//host/computer/dir")
   ("//host/computer", "/dir")
>>> splitext('bar')
   ('bar', '')
>>> splitext('')
   ('', '.exe') >>>
   ('/foo/bar', '.exe')
>>> splitext('.cshrc')
   ('.cshrc', '') >>>
   ('/foo/....jpg', '')

Suggestion : 4

Last Updated : 22 Jan, 2022

1. time() :- This function is used to count the number of seconds elapsed since the epoch.
2. gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds from epoch. If no seconds are mentioned, time is calculated till present. The structure attribute table is given below. 

Index Attributes Values
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61(60 or 61 are leap - seconds)
6 tm_wday 0 to 6
7 tm_yday 1 to 366
8 tm_isdst - 1, 0, 1 where - 1 means
Library determines DST


Seconds elapsed since the epoch are: 1470121951.9536893
Time calculated given seconds is:
   time.struct_time(tm_year = 2016, tm_mon = 8, tm_mday = 2,
      tm_hour = 7, tm_min = 12, tm_sec = 31, tm_wday = 1,
      tm_yday = 215, tm_isdst = 0)