Is there a straightforward way to parse date in Bash with year and month only, eg in format YYYY-mm
?
This does not work:
$ date -d "2022-12" "%Y-%m"
date: invalid date ‘2022-12’
In Python, this works:
>>> from datetime import datetime
>>> datetime.strptime("2022-12", "%Y-%m")
datetime.datetime(2022, 12, 1, 0, 0)
CodePudding user response:
Correct command is (at least it works for me MacOS):
date -jf "%Y-%m" "2022-12"
>Wed Dec 21 12:45:05 IST 2022
In your case date is incorrect since you doin't have day. The solution is simply add '01' day to source date:
my_date='2022-12'
date --date="${my_date}-01"
>Thu Dec 1 00:00:00 UTC 2022
CodePudding user response:
Create a function with a default daynumber (possible in .bashrc
)
ymdate() {
date -d "$1-1" "%Y-%m-%d"
}
Next call the function like
ymdate 2022-12