So I am trying to rename some files to the time in their creation date using os.stat("file").st_stat. Then I pop the superfluous information, I only need the time because they are already sorted by date in dated folders. The code is kind of spaghetti, i am still a beginner after all. I use so many str() because sometimes I get 'None' objects from os.listdir() and i got some error trying to format integers in strings. So the problem is that it doesn't work properly. I got rid of all the errors, and boy they were many, but it doesn't rename to a timestamp. I get stuff like this "0R3IJL~J". And it changes with the timestamp. That makes me think that it is somehow related to time and that it can be fixed.
The files that I am trying to rename are .h264 and I am working on Raspbian, on a Raspberry Pi Zero W.
Here are some more examples of the names I am getting: 06RR8I~Y, 0OFKLJ~J, 0O5KZV~I, 0PJJ0D~V.
import os
import datetime
dates = []
for i in range(1,7):
if 1 <= i <= 6:
i = "0{}".format(str(i))
for j in range(1,31):
if 1 <= j <= 9:
j = "0{}".format(str(j))
dates.append("2019-{}-{}".format( i, j))
for dt in dates:
if os.path.exists(str(dt)):
os.chdir(str(dt))
for fil in os.listdir("."):
created = os.stat(str(fil)).st_ctime
da_cr = str(datetime.datetime.fromtimestamp(created))
print type(da_cr)
li_cr = list(da_cr)
if li_cr[-7] == ".":
for i in range(7):
li_cr.pop(-1)
for i in range(11):
li_cr.pop(0)
nn = "".join(l_c for l_c in li_cr)
print fil
os.rename(fil, str(nn))
os.chdir("../")
I guess this will do the trick for you but bear in mind you will need to implement a lot of checks to make it safer. I just rewrote and simplify your code without taking care of safety checks.
import os
from datetime import datetime
dates = []
for i in range(1, 7):
for j in range(1, 31):
dates.append("2019-%0.2d-%0.2d" % (i, j))
for date in dates:
if os.path.exists(date):
os.chdir(date)
for filename in os.listdir("."):
timestamp = datetime.fromtimestamp(os.stat(filename).st_ctime)
os.rename(filename, timestamp.time())
os.chdir("..")