Home > Software design >  Work out if date is in current week python
Work out if date is in current week python

Time:09-24

I'm trying to write a bit of code to check if a document has been updated this week, and if not to read in the data and update it. I need to be able to check if the last modified date/time of the document occurred in this week or not (Monday-Sunday).

I know this code gives me the last modified time of the file as a float of secconds since the epoch:

os.path.getmtime('path')

And I know I can use time.ctime to get that as a string date:

time.ctime(os.path.getmtime('path'))

But I'm not sure how to check if that date was in the current week. I also don't know if its easier to convert to a datetime object rather than ctime for this?

CodePudding user response:

you can use datetime.isocalendar and compare the week attribute, basicallly

import os
from datetime import datetime

t_file = datetime.fromtimestamp(os.path.getmtime(filepath))
t_now = datetime.now()

print(t_file.isocalendar().week == t_now.isocalendar().week)
# or print(t_file.isocalendar()[1]== t_now.isocalendar()[1])

# to compare the year as well, use e.g.
print(t_file.isocalendar()[:2] == t_now.isocalendar()[:2])

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

  • Related