Python dealing with dates and times

I am looking for a solution for the following:

Given today's date, find out what month it was. So, 2 should be back for today, as this is currently a march, the third month of the year. 12 is due back in January.

Then, based on this, I need to be able to iterate through the directory and find all the files created this month.

Bonus points will include a search for the most recent file created in the previous month.

+4
source share
5 answers

The simplest is where adate is an instance of datetime.date :

 def previousmonth(adate): m = adate.month - 1 return m if m else 12 

On most Unix file systems, there is no real way to determine when a file was created, because they simply do not support this information. Perhaps you need a "last time changing the inode" (there may be a creation, there may be another inode change):

 import os, datetime def cmonth(filename): ts = os.stat(filename).st_ctime return datetime.date.fromtimestamp(ts).month 

Of course, this can mean this month in any year - are you sure that in both issues you do not need a year , as well as a month? This will be the .year attribute.

In any case, sticking to only a month, according to your question, for one directory (which is the letter of your question) to get all the files that you can use os.listdir (for a tree embedded in the directory that you use os.walk ). Then, to save only those with the last-inode-change for a specific month:

 def fileswithcmonth(dirname, whatmonth): results = [] for f in os.listdir(dirname): fullname = os.path.join(dirname, f) if whatmonth == cmonth(fullname): results.append(fullname) return results 

You can code this as a list comprehension, but there is too much code to make listcomp elegant and concise.

To get the β€œlast” time, you can either repeat the os.stat call (slower, but probably easier), or change cmonth to return the timestamp. Taking a simple route:

 def filetimestamp(fullname): return os.stat(fullname).st_ctime 

Now the "most recent file" specified in the files list of full file names (i.e., inc. Path),

 max(files, key=filetimestamp) 

Of course, there are many degrees of freedom in how you combine all this depending on your specific characteristics - given that the specifications do not necessarily seem accurate or complete. I decided to show building blocks that you can easily customize and combine your specific needs, rather than a full-blown solution that is likely to solve a problem that is slightly different from your actual one; -).

Edit : since the OP clarified that they need a year and a month, let's see what changes will be needed using the ym tuples for (year, month) instead of the bare month:

 def previousym(adate): y = adate.year m = adate.month - 1 return (y, m) if m else (y - 1, 12) import os, datetime def cym(filename): ts = os.stat(filename).st_ctime dt datetime.date.fromtimestamp(ts) return cym.year, cym.month def fileswithcym(dirname, whatym): results = [] for f in os.listdir(dirname): fullname = os.path.join(dirname, f) # if you need to avoid subdirs, uncomment the following line # if not os.path.isfile(fullname): continue if whatym == cym(fullname): results.append(fullname) return results 

Nothing serious or complicated, as you can see (I also added comments to show how to skip subdirectories if you are worried about this). And btw, if you really need to walk in a subtree, and not just with a directory, this change is also quite localized:

 def fileswithcymintree(treeroot_dirname, whatym): results = [] for dp, dirs, files in os.walk(treeroot_dirname): for f in files: fullname = os.path.join(dp, f) if whatym == cym(fullname): results.append(fullname) return results 
+3
source

It's pretty easy to find the previous month - see, for example, Alex Martelli's answer - but finding the last file created this month is a little harder:

 from datetime import date import os def filesLastMonth(directory): """ Given a directory, returns a tuple containing 1. A list with all files made in the previous month (disregards year...) 2. The file most recently created in the previous month """ def fileCreationTime(filePath): return os.path.getctime(filePath) today = date.today() lastMonth = today.month-1 if today.month != 1 else 12 # gets each item in the directory that was created last month createdLastMonth = [item for item in os.listdir(directory) if date.fromtimestamp(os.path.getctime(item)).month == lastMonth] # and this is the most recent of the above mostRecentlyLastMonth = max(createdLastMonth, key=fileCreationTime) return (createdLastMonth, mostRecentlyLastMonth) 

You can use os.path.getctime on Windows to get the path creation time, but this does not work on Unix - the creation time is not saved in this case (you just get the time of the last change).

+2
source

Some questions are asked here ...

+1
source

http://docs.python.org/library/datetime.html

At the beginning of the previous month from the date

 def first_of( today ) yr_mn = today.year*12 + (today.month-1) - 1 return datetime.date( year= yr_mn//12, month= yr_mn%12+1, day=1 ) 

You can then use this with os.walk to find the files in question.

0
source

Data processing is performed trivially with a library such as Labix python-dateutil.

You want to do something like this:

 In [8]: from dateutil.relativedelta import relativedelta In [9]: from datetime import date In [10]: d = date(2010,2,12) In [11]: print (d-relativedelta(months=1)).month 1 In [12]: print (date(2010,1,4)-relativedelta(months=1)).month 12 
0
source

Source: https://habr.com/ru/post/1305694/


All Articles