날짜: 연도와 주 번호로 시작, 월요일 날짜를 구하는 방법

날짜: 연도와 주 번호로 시작, 월요일 날짜를 구하는 방법

특정 주의 월요일 ISO 날짜를 얻는 방법은 무엇입니까? 예를 들어 2021년 32번째 주 월요일?

내가 출마하면 date -dmonday +%Y%m%d이번 주 월요일 날짜를 알 수 있습니다. 2021and 를 32변수로 전달하고 해당 주의 월요일 날짜를 어떻게 얻을 수 있습니까 ?

답변1

이것은 잘 작동하는 것 같습니다.

#! /bin/bash
year=$1
week=$2

read s w d < <(date -d $year-01-01T13:00 '+%s %V %u')
(( s += ((week - w) * 7 - d + 1) * 24 * 60 * 60 ))

date -d @$s '+%V:%w %Y-%m-%d %a'

시험용

for y in {1970..2022} ; do
    maxw=$(date +%V -d $y-12-31)
    if (( max == 1 )) ; then  # The last day of the year belongs to week #1.
        max=52
    fi
    for ((w=1; w<=maxw; ++w)) ; do
        date.sh $y $w | tail -n1 | grep -q "0\?$w:1 " || echo $y $w
    done
done

date.sh위의 스크립트는 어디에 있습니까?

답변2

Wikipedia에는 ​​ISO 주간 날짜에 대한 기사가 있습니다. "첫 번째 주"는 첫 번째 목요일이 있는 주로 정의됩니다. 기사에서는 이것이 1월 4일이 항상 1주차에 ​​해당하는 것과 같다고 지적합니다. GNU Date를 사용하면 다음과 같은 날짜를 지정할 수 있습니다 date -d "Jan 4 2021 +3 weeks".날짜는 일반적으로 월요일이 아닌 넷째 주에 있습니다.

날짜를 사용하여 요일을 찾아 요청할 날짜를 조정하는 데 사용할 수 있습니다.

#!/bin/bash
# pass in $1 as the week number and $2 as the year
# Make sure we are no going to be bothered by daylight saving time
# Use explicit time idea from https://unix.stackexchange.com/a/688968/194382
export TZ=UTC
# Jan 4th is always in week 1. ask for the day of the week that is
# $1-1 weeks ahead. %u gives 1 for Monday, 2 for tuesday, ...
weekday=$(date -d"13:00 Jan 4 $2 +$(($1 -1)) weeks" "+%u")
# So now just go back 0 days for a monday, 1 day for tuesday ...
# Could use Jan 5 and go back 1 day for monday instead.
date -d"13:00 Jan 4 $2 +$(($1 -1)) weeks -$((weekday -1)) days" "+%a %F (%G %V)"

따라서 2021년의 경우 첫 번째 주의 월요일은 2021-01-04이고 2020년의 경우 2019-12-30(예: 전년도 말)임을 나타냅니다.

답변3

이는 최소 2000년부터 2025년까지 유효합니다.

Y=2021
W=32
LC_ALL=C date -d"${Y}0101 ${W} week -$(date -d"${Y}0104" +%u) day -3day"
Mon Aug  9 00:00:00 CEST 2021

접두사는 효과를 LC_ALL=C제거합니다 .locale

답변4

이 작업은 oneliner를 사용하여 Python을 통해 수행할 수 있습니다.

echo "2021 32"| python3 -c 'import datetime as dt; print(dt.datetime.strptime(input()+" 1", "%G %V %u").strftime("%Y-%m-%d"));'
2021-08-09

이것을 BASH 함수로 래핑하고 수요일(요일=3)과 같이 1~7주의 다른 요일에 대해 명시적으로 사용할 수 있습니다.

> iso_year_week_day() {  echo "$1 $2 $3" | python3 -c 'import datetime as dt; print(dt.datetime.strptime(input(), "%G %V %u").strftime("%Y-%m-%d"));'; }
>
> iso_year_week_day 2021 32 3
2021-08-11
> iso_year_week_day 2022 52 7
2023-01-01
> q=$(iso_year_week_day 2021 32 3)
> echo $q
2021-08-11

PS 물론 출력 형식은 편집을 통해 쉽게 조정할 수 있습니다.strftime("%Y-%m-%d")

관련 정보