Python Forum
Convert string to path using Python 2.7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert string to path using Python 2.7
#1
Greetings!
I need to find yesterday's modified directories.

but a PC I'm running the code on has Python 2.7 and I cannot use pathlib...
The code I have has a problem (see the error below), I can't get a Path from the string..
"AttributeError: 'str' object has no attribute 'stat'"

I Googled for an answer for about an hour or so but could not find a solution... Confused
Here is the code I got so far:
import os.path
import datetime as dt

tz ='C:\\01'
for dr_name in os.listdir(tz):
    dr_path = os.path.join(tz, dr_name)
    print(type(dr_path)) ## <-- it is alredy a string not Path
    if os.path.isdir(dr_path): 
        print("Directory path name:", dr_path)
        print(type(dr_path))        
        np = os.path.normpath(dr_path) 
        print(type(np))  ## <-- Still string
        yesterday = dt.datetime.now().date() - dt.timedelta(days=1)
        if yesterday == dt.datetime.fromtimestamp(np.stat().st_mtime).date():
            print(f"  Directory modified yesterday -> {np}")
Thank you!
Reply
#2
Please try to upgrade to python3.

os.path.* methods are mostly string manipulations. They return paths in the form of a string, not a path object. So after you get the normpath in np, you could gather the stat object with
filestat = os.stat(np)
There is a backport for pathlib to 2.7 in https://pypi.org/project/pathlib2/. I haven't tried it.
Reply
#3
	
filestat = os.stat(np)
It works but How I can use it ?
It produces an error if I use filestat instead if np in "IF"
Error:
if yesterday == dt.datetime.fromtimestamp(filestat.stat().st_mtime).date():
AttributeError: 'os.stat_result' object has no attribute 'stat'
I wish I could install Python 3.x on the PCs, but they are not under my control... Sad
Reply
#4
I made changes to the code, I think I'm very close but failing to compare 2(two) time stamps.
yesterday var is formated as YYYY-MM-DD
and the ts var as YYYY-MM-DD HH:MM:SS.milliseconds

for dr_name in os.listdir(tz):
    dr_path = os.path.join(tz, dr_name)
    if os.path.isdir(dr_path): 
        print("Directory path name:", dr_path)       
        yesterday = dt.datetime.now().date() - dt.timedelta(days=1)
        ts = datetime.datetime.fromtimestamp(os.path.getmtime(dr_path))
        print(f" File T_stamp > {ts}")
        if datetime.datetime.fromtimestamp(os.path.getmtime(dr_path)) == yesterday:
            print(f" Yesterday file -> {dr_path}")
Reply
#5
In line 5 you start with a datetime (from now()), but then convert it into a date (with .date()).

In line 8 you're comparing a timestamp to a date which won't match. What you might want is to compare the date of that timestamp with your yesterday date.

if datetime.datetime.fromtimestamp(os.path.getmtime(dr_path)).date() == yesterday:
Another preference might be to see if the timestamp lies between two datetime() timestamps.
Reply
#6
Chain comparison operators and don't compare if datetimes are equal.

import datetime
import os


def iterdirs(root, min_days_age=0, max_days_age=1):
    now = datetime.datetime.now()

    # not newer than end_date
    end_date = now - datetime.timedelta(days=min_days_age)

    # not older than start_date
    start_date = now - datetime.timedelta(days=max_days_age)

    for path in os.listdir(root):
        if not os.path.isdir(path):
            # if path is not a directory, skip it
            # processing only directories
            continue

        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
        
        # chaining comparison operators:
        # https://www.geeksforgeeks.org/chaining-comparison-operators-python/
        if start_date <= mtime <= end_date:
            yield path
tester_V and snippsat like this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
Thank you Dead YeY!
I see your point....
Reply
#8
Greetings to all that work on this Friday night! Wink
I just found I have no idea how to use the snippet Dead YeY shared. Sad
it seems the function name is "iterdir" and if I call it the script errors out...
So,"iterdir" is not function name.
How do I call it?
Is the "root" is my directory to scan?

It looks very elegant but I cannot use it.
 
def iterdirs(root, min_days_age=0, max_days_age=1):
    now = datetime.datetime.now()
 
    # not newer than end_date
    end_date = now - datetime.timedelta(days=min_days_age)
 
    # not older than start_date
    start_date = now - datetime.timedelta(days=max_days_age)
 
    for path in os.listdir(root):
        if not os.path.isdir(path):
            # if path is not a directory, skip it
            # processing only directories
            continue
 
        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
         
        # chaining comparison operators:
        # https://www.geeksforgeeks.org/chaining-comparison-operators-python/
        if start_date <= mtime <= end_date:
            yield path
Reply
#9
tester_V Wrote:if I call it the script errors out...
That's not a good error report for the forum. If there is an error, post at least the complete exception traceback that Python prints on the console.

Also, what is this PC where you can't install Python 3? Get a new one. Python 3 has been around since 2009, and producing Python 2 code is just a waste of time.
tester_V likes this post
Reply
#10
(Nov-20-2021, 08:51 AM)Gribouillis Wrote: Also, what is this PC where you can't install Python 3? Get a new one. Python 3 has been around since 2009, and producing Python 2 code is just a waste of time.

Probably a work PC or a library or something of that sort....

Indeed writing Python 2 code is a waste of time.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  convert string to float in list jacklee26 6 1,815 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  how to convert tuple value into string mg24 2 2,237 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  -i option changes sys.path (removes leading empty string '') markanth 6 1,899 Aug-26-2022, 09:27 PM
Last Post: markanth
  Convert string to float problem vasik006 8 3,269 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 2,421 May-13-2022, 07:28 PM
Last Post: mikepy
Question How to convert string to variable? chatguy 5 2,231 Apr-12-2022, 08:31 PM
Last Post: buran
  Convert string to int Frankduc 8 2,395 Feb-13-2022, 04:50 PM
Last Post: menator01
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,149 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  Convert each element of a list to a string for processing tester_V 6 5,170 Jun-16-2021, 02:11 AM
Last Post: tester_V
Question convert unlabeled list of tuples to json (string) masterAndreas 4 7,355 Apr-27-2021, 10:35 AM
Last Post: masterAndreas

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020