Extracting creation-minute of a file in Python

253 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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
3
On

You could use modulo on the actual ctime result:

from pathlib import Path
p=Path('/tmp/file')

Then take the ctime result and remove everything but the time portion of the time stamp:

ctime_tod=p.stat().st_ctime % (60*60*24) # just the time portion

Then use divmod to get the minutes and seconds:

m, s = map(int, divmod(ctime_tod, 60))   # just minutes and seconds

m will have the minute portion of the file creation and s the seconds. Be aware that the time stamp on most OSs will be in UTC where time.ctime converts to local time.