1

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)
petervanya
  • 306
  • 4
  • 11
  • please, review next posts: https://stackoverflow.com/questions/1842634/parse-date-in-bash – drFunJohn Dec 21 '22 at 11:02
  • I did, sadly there is no (simple) answer addressing my question. I did not account for rather complicated substitutions using `sed` and other tricks. – petervanya Dec 21 '22 at 11:20
  • To see what datetime formats are valid for GNU date `-d`, read [29 Date input formats](https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html#Date-input-formats). TL;DR omitting the year is OK, omitting the day is not. – glenn jackman Dec 21 '22 at 14:35

3 Answers3

0

Python is more flexible when it comes to date formats. It can accept different formats, such as "2022-12". However, the date command in bash requires a valid date format to be specified such as "2022-12-01" or "2022-12-31".

apan
  • 353
  • 3
  • 11
0

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
drFunJohn
  • 199
  • 4
0

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
Walter A
  • 19,067
  • 2
  • 23
  • 43