ISO 8601, an international standard covering the exchange of date and time-related data, as the string format. The ISO calendar is a widely used variant of the Gregorian calendar. 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.
In this article, I will talk about:
- Basic ISO 8601 calendar elements
datetime.dateto ISO 8601 format
- Parsing an ISO 8601-formatted date
Basic ISO 8601 calendar elements
ISO year & ISO week
The first week of year 2019 is from 31th December 2018 to 6th January 2019, we
want the year of 31th December 2018 to be 2019, in this case we can apply
isocalendar() in order to getting the ISO year, same for ISO weekday.
There are several mutually equivalent and compatible descriptions of week 01:
- the week with the year’s first Thursday in it (the formal ISO definition)
- the week with 4 January in it
- the first week with the majority (four or more) of its days in the starting year
- the week starting with the Monday in the period 29 December – 4 January
2018-12-31’s year is 2018, but its ISO year is 2019. In this case, we
isocalendar() to achieve it.
isoweekday() returns different results from
weekday(), it presents value 1
Converting date to ISO 8601 format
Calendar date includes 3 principal elements:
indicates a four-digit year, 0000 through 9999,
MM indicates a two-digit
month of the year, 01 through 12,
DD indicates a two-digit day of that month,
01 through 31.
As the example above, we need to pay attention one-digit month or day value is
datetime.date value and
isoformat value. ISO month and
day are always two-digit value.
Parsing an ISO 8601-formatted date
Specifically, this function supports strings in the format(s)
Caution: This does not support parsing arbitrary ISO 8601 strings - it is
only intended as the inverse operation of
dateutil.parser offers a generic date/time string parser which is able to
parse most known formats to represent a date and/or time.
parses a string in one of the supported formats.