1

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?

Emi OB
  • 2,814
  • 3
  • 13
  • 29

1 Answers1

4

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • the .week bit doesn't work for me, I get `AttributeError: 'tuple' object has no attribute 'week'`, but I can just use [1] instead. Comparing year and week is good though! This gives me what I need :) – Emi OB Sep 24 '21 at 11:32
  • also, does importing timezone do anything? – Emi OB Sep 24 '21 at 11:34
  • 1
    @EmiOB you can set a time zone (sorry for the confusing import), however I don't think it matters since you'd set the same for both datetime objects. In my example, I use naive datetime (tz not set), so both are local time of your machine. – FObersteiner Sep 24 '21 at 11:40