Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Date in Bash

Tags:

date

bash

parsing

How would you parse a date in bash, with separate fields (years, months, days, hours, minutes, seconds) into different variables?

The date format is: YYYY-MM-DD hh:mm:ss

like image 353
Steve Avatar asked Dec 03 '09 20:12

Steve


People also ask

How do you parse a date in python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.


2 Answers

Does it have to be bash? You can use the GNU coreutils /bin/date binary for many transformations:

 $ date --date="2009-01-02 03:04:05" "+%d %B of %Y at %H:%M and %S seconds"  02 January of 2009 at 03:04 and 05 seconds 

This parses the given date and displays it in the chosen format. You can adapt that at will to your needs.

like image 196
Dirk Eddelbuettel Avatar answered Oct 11 '22 13:10

Dirk Eddelbuettel


This is simple, just convert your dashes and colons to a space (no need to change IFS) and use 'read' all on one line:

read Y M D h m s <<< ${date//[-:]/ } 

For example:

$ date=$(date +'%Y-%m-%d %H:%M:%S') $ read Y M D h m s <<< ${date//[-: ]/ } $ echo "Y=$Y, m=$m" Y=2009, m=57 
like image 34
NVRAM Avatar answered Oct 11 '22 13:10

NVRAM