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?
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
I have a Deephaven DateTime in the New York (US-East) timezone and I'd like to get the year, month, and day (of the month) numbers from it as integers in Python.
Deephaven's time module has these utilities. You may have used it to create a Deephaven DateTime in the first place.
from deephaven import time as dhtu
timestamp = dhtu.to_datetime("2022-04-01T12:00:00 NY")
The following three methods will give you what you're looking for:
year - Gets the year
month_of_year - Gets the month
day_of_month - Gets the day of the month
All three methods will give you what you want based on the DateTime itself and your preferred time zone.
tz_ny = dhtu.TimeZone.NY
year = dhtu.year(timestamp, tz_ny)
month = dhtu.month_of_year(timestamp, tz_ny)
day = dhtu.day_of_month(timestamp, tz_ny)
I have a table which contains information on the number of changes done on a particular day. I want to add a text field to it in the format YYYY-WW (e. g. 2022-01) which indicates the week number of the day. I need this information to determine in what week the total number of changes was the highest.
How can I determine the week number in Python?
Below is the code based on this answer:
week_nr = day.isocalendar().week
year = day.isocalendar().year
week_nr_txt = "{:4d}-{:02d}".format(year, week_nr)
At a first glance it seems to work, but I am not sure that week_nr_txt will contain year-week tuple according to the ISO 8601 standard.
Will it?
If not how do I need to change my code in order to avoid any week-related errors (example see below)?
Example of a week-related error: In year y1 there are 53 weeks and the last week spills over into the year y1+1.
The correct year-week tuple is y1-53. But I am afraid that my code above will result in y2-53 (y2=y1+1) which is wrong.
Thanks. I try to give my answer. You can easily use datetime python module like this:
from datetime import datetime
date = datetime(year, month, day)
# And formating the date time object like :
date.strftime('%Y-%U')
Then you will have the year and wich week the total information changes
I'm running Python 3.8.3 and I found something weird about the ISO Week format (%V) :
The first day and the last day of 2019 are both in week 1.
from datetime import date
print(date(2019, 1, 1).strftime('%Y-W%V'))
print(date(2019, 12, 29).strftime('%Y-W%V'))
print(date(2019, 12, 31).strftime('%Y-W%V'))
Output:
2019-W01
2019-W52
2019-W01
Why does it behave like that?
It is fully correct.
As you see in your dates, all of them are in 2019, so it is correct to get 2019 with %Y.
Week number is defined by ISO, and so one week could be considered in previous or in next year.
You need to use %G to get year of the week number (%V).
This is for Python:
I need a library that is able to do arithmetic operations on dates while taking into account the duration of a month and or year.
For example, say I add a value of "1 day" to 3/31/2020, the result of should return:
1 + 3/31/2020 = 4/1/2020.
I also would need to be able to convert this to datetime format, and extract day, year and month.
Does a library like this exist?
import datetime
tday = datetime.date.today() # create today
print("Today:", tday)
""" create one week time duration """
oneWeek = datetime.timedelta(days=7)
""" create 1 day and 1440 minutes of time duraiton """
eightDays = datetime.timedelta(days=7, minutes=1440)
print("A week later than today:", tday + oneWeek) # print today +7 days
And the output to this code snippet is:
Today: 2020-03-25
A week later than today: 2020-04-01
>>>
As you see, it takes month overflows into account and turns March to April. datetime module has lots of things, I don't know all its attributes well and haven't used for a long time. However, I believe you can find nice documentation or tutorials on the web.
You definitely can create any specific date(there should be some constraints though) instead of today by supplying day, month and year info. I just don't remember how to do it.
I am trying to get a date based on a number of the week, but there are some annoyances.
The date.weekday() returns the day of the week where 0 in Monday and 6 is Sunday.
The %w directive of date.strftime() and date.strptime() uses the 0 for Sunday and 6 for Saturday.
This causes some really annoying issues when trying to figure out a date given a week number from date.weekday().
Is there a better way of getting a date from a week number?
EDIT:
Added the example.
import datetime
original_date = datetime.date(2014, 8, 24)
week_of_the_date = original_date.isocalendar()[1] # 34
day_of_the_date = original_date.isocalendar()[2] # 7
temp = '{0} {1} {2}'.format(*(2014, week_of_the_date, day_of_the_date-1))
date_from_week = datetime.datetime.strptime(temp, '%Y %W %w')
week_from_new_date = date_from_week.isocalendar()[1] # 35!!
EDIT 2:
I ultimately put the date stuff in the view (using jQuery UI), it has more consistent notions of weeks.
I think the Sunday vs. Monday distinction between weekday and strftime using %W is moot - you could use isoweekday to get those to line up, or %U in strftime if you wanted Sunday as the first day of the week. The real problem is that strftime, based on the underlying C function, determines the first week of the year differently than the ISO definition. With %W the docs say: " All days in a new year preceding the first Monday are considered to be in week 0". ISO calendars count the week containing the first Thursday as the first week, for reasons I do not understand.
Two ways I found to work with ISO weeks, either just getting datetime.date instances back or supporting a variety of operations, are:
this answer with a simple timedelta approach:
What's the best way to find the inverse of datetime.isocalendar()?
this third-party library: https://pypi.python.org/pypi/isoweek/