The datetime
module provides a method date.isocalendar
that, given a date, returns it in the format ([year], [week], [weekday])
. How do I go backwards? Given a ([year], [week], [weekday])
tuple, how can I get a date
object?
Isocalendar() Method Of Datetime Class In Python The isocalendar() function is used to return a tuple of ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week. Therefore, ISO years always start with Monday.
Use the isinstance built-in function to check if a variable is a datetime object in Python, e.g. if isinstance(today, datetime): . The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.
Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.
EDIT Found question with solution: What's the best way to find the inverse of datetime.isocalendar()?
My solution had mistakes. On googling saw previous question which upon testing below worked. (See top answered question in above link for definition of iso_to_gregorian
). (Basically find iso year start date and then use timedelta to find current date from day and week number.
for i in range(-10000,10000,1):
x = datetime.datetime.today().date() + datetime.timedelta(i)
x_iso = datetime.datetime.isocalendar(x)
assert iso_to_gregorian(*x_iso) == x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With