2

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?

Marcel Sonderegger
  • 772
  • 1
  • 8
  • 21

2 Answers2

2

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
fixmycode
  • 8,220
  • 2
  • 28
  • 43
  • 1
    just a comment, I try to think of a use case for this measurement but it escapes me, this will return very different values for files created near midnight on consecutive days. – fixmycode Dec 15 '20 at 19:03
  • that's already better. The use case: I got a programm which updates the modification time to the time of now. So at the end in the folder are unupdated files, which have the original timestamp. As it is for accounting, the creation date does not change, just the time. Now I am writing a programm to treat the missed files. – Marcel Sonderegger Dec 15 '20 at 19:30
1

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.

dawg
  • 98,345
  • 23
  • 131
  • 206