Search code examples
pythonpython-3.xfiletimeminute

Extracting creation-minute of a file in Python


I need to extract the creation-minute of a file. But not the date. As an example of a file which was created on:

Tue Jul 31 22:48:58 2018

the code should print 1368 (result from:22hours*60+24minutes)

I got the following program which works perfectly, but in my eyes is ugly.

import os, time

created=time.ctime(os.path.getctime(filename)) # example result: Tue Jul 31 22:48:58 2018
hour=int(created[11:13])
minute=int(created[14:16])
minute_created=hour*60+minute

print (minute_created)

As I like to write beautiful code, here my question: Is there a more elegant way to do it in Python?


Solution

  • Using regular expressions:

    import os, time, re
    
    time = time.ctime(os.path.getctime(filename))
    hours, mins, secs = map(int, re.search(r'(\d{2}):(\d{2}):(\d{2})', time).groups())
    minutes_created = hours*60+mins
    minutes_created_fr = minutes_created + secs/60 # bonus with fractional seconds